2017-03-04 9 views
0

私はMashapeマーケットプレイスを通じてインターネットゲームデータベースAPIを使用するAndroid APPを構築しています。私は取得要求に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(); 

をし、これは私が、私も@Fieldで試してみました。この

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

しかし、運を使用しようとした私のレトロフィットインタフェース

public interface GamesAPIService { 

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

} 

ですが、どちらもうまくいきませんでした。何か案は?ありがとう。

編集:私が"?fields=name,release_dates"を追加したときに明確にすると、401 Unauthorized Errorが発生します。

+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 
     } 
    }); 
} 
関連する問題