2017-03-04 55 views
0

我正在構建一個Android應用程序,我在其中使用通過Mashape市場的Internet遊戲數據庫API。我正在使用Retrofit獲取請求,並從API獲取數據需要API密鑰。使用Retrofit添加字段到URL

我得到它的工作,但API只返回遊戲ID和我想要的遊戲名稱和其他信息,但我不知道如何添加字段。這是Mashape如何查詢它:

HttpResponse<String> response = Unirest.get("https://igdbcom-internet-game-database-v1.p.mashape.com/games/?fields=name%2Crelease_dates") 
.header("X-Mashape-Key", "API KEY HERE") 
.header("Accept", "application/json") 
.asString(); 

,這是我更新接口

public interface GamesAPIService { 

    @GET("/games/") 
    Call<List<GamesResponse>> gameList(@Query("mashape-key") String apikey); 

} 

我試圖用這個

@GET("/games/?fields=name,release_dates") 

,但沒有運氣,我也試圖與@Field但也沒有工作。有任何想法嗎?謝謝。

編輯:只是爲了澄清當我添加"?fields=name,release_dates"我得到401未經授權的錯誤。

+0

爲什麼你有'@Query(「mashape-key」)String apikey'?您在URL中沒有'?mashape-key = ...'...關鍵需要是標題,而不是查詢參數。 –

+0

我試過@Header來傳遞apikey,或者在作爲「.addHeader」的活動本身中,它從來沒有工作過,但是它出於某種原因這樣工作,所以我保留了它。 – Prime47

回答

1

首先,我認爲你需要爲你的所有請求添加mashape鍵。

OkHttpClient httpClient = new OkHttpClient(); 
httpClient.addInterceptor(new Interceptor() { 
    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request().newBuilder() 
      .addHeader("X-Mashape-Key", "API_KEY_HERE") 
      .addHeader("Accept", "application/json") 
      .build(); 
     return chain.proceed(request); 
    } 
}); 
Retrofit retrofit = new Retrofit.Builder() 
    .baseUrl("https://igdbcom-internet-game-database-v1.p.mashape.com") 
    .client(httpClient) 
    .build(); 

然後這是信息查詢。

public interface GamesAPIService { 
    @GET("/games") 
    Call<List<GamesResponse>> gameList(@Query("fields") String value); 
} 

最後一件事情是打電話。

GamesAPIService gamesAPIService = retrofit.create(GamesAPIService.class); 

Call<List<GamesResponse>> call = gamesAPIService.gameList("name,release_dates"); 
if (call!=null){ 
    call.enqueue(new Callback<List<GamesResponse>>() { 

     @Override 
     public void onResponse(Call<List<GamesResponse>> call, Response<List<GamesResponse>> response) { 
      // handle success 
     } 

     @Override 
     public void onFailure(Throwable t) { 
      // handle failure 
     } 
    }); 
}