2016-10-22 24 views
0

正如問題中提到的,我需要構建一個API接口進行改造。這是我的網址:如何構建API接口進行改造?

https://api.flightstats.com/flex/weather/rest/v1/json/all/COK?appId=XXXXXXXXX&appKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&codeType=IATA 
//--------------------------------------------------------^^^-------------------------------------------------------------------- 

如上標示,問題就出在位置COK,這是一個機場代碼,我需要它傳遞的要求,但我不能把它傳給我在執行改造界面的創建。這是我的代碼:

WeatherApiClient.class

public class WeatherApiClient { 

    public static final String BASE_URL = "https://api.flightstats.com/flex/weather/rest/v1/json/all/"; 
    private static Retrofit retrofit = null; 


    public static Retrofit getClient() { 
     if (retrofit==null) { 
      retrofit = new Retrofit.Builder() 
        .baseUrl(BASE_URL) 
        .addConverterFactory(GsonConverterFactory.create()) 
        .build(); 
     } 
     return retrofit; 
    } 
} 

WeatherApiInterface.class

public interface WeatherApiInterface { 
    @GET("COK") // this should be dynamic 
    Call<WeatherPojo> getValues(@Query("appId") String appId, @Query("appKey") String key, @Query("codeType") String code); 
} 

我應該如何改變我的代碼,這樣我也可以通過機場的代碼,同時使一個要求?

+0

我不太瞭解改造,但如何爲getValues()添加「COK」?而且你需要位置的查詢鍵。 (它應該是查詢字符串中的someKey = COK。) – Toris

+0

也許@Get(「。」)或者類似的。 – Toris

回答

0

試試這個intreface代碼,

public interface WeatherApiInterface{ 
    @GET("{id}") 
    Call<WeatherPojo> getValues(@Path("id") String airportId, @Query("appId") String appId, @Query("appKey") String key, @Query("codeType") String code); 
} 

你如何調用這個你還沒有顯示。所以我認爲這很好。

+0

不,它不起作用! – OBX

+0

什麼是錯誤?對我來說就像一個魅力。我應該添加我的整個代碼嗎? –

0

作爲您的問題,您已經創建了Retrofit實例。

public static final String BASE_URL = "https://api.flightstats.com/flex/weather/rest/v1/json/all/"; 
    private static Retrofit retrofit = null; 
    public static Retrofit getClient() { 
     if (retrofit==null) { 
      retrofit = new Retrofit.Builder() 
        .baseUrl(BASE_URL) 
        .addConverterFactory(GsonConverterFactory.create()) 
        .build(); 
     } 
     return retrofit; 

你還別說在你的代碼中的Endpoint.This編碼詳細介紹 參數和要求的方法。

public interface WeatherApiInterface 
    { @GET("COK") 
    //----^^^-- 
     Call<WeatherPojo> getValues(@Query("appId") String appId, @Query("appKey") String key, @Query("codeType") String code); 
    } 

但是在代碼中缺少一部分它是您的異步​​操作。將此代碼放入您的活動課程中。

ApiInterface apiService = 
       ApiClient.getClient().create(WeatherApiInterface.class); 

     Call<WeatherPojo> call = apiService.getValues(appId,appKey,codeType); 
     call.enqueue(new Callback<WeatherPojo>() { 
      @Override 
      public void onResponse(Call<WeatherPojo>call, Response<WeatherPojo> response) { 
       List<Movie> movies = response.body().getResults(); 
       Log.d(TAG, "Number of movies received: " + movies.size()); 
      } 

      @Override 
      public void onFailure(Call<WeatherPojo>call, Throwable t) { 
       // Log error here since request failed 
       Log.e(TAG, t.toString()); 
      } 
     });