web-dev-qa-db-ja.com

レトロフィットの動的パス

http://192.168.1.64:5050/api/{api_key}/updater.infoのようなリソースにアクセスしようとしています。

api_keyパラメータを動的に設定するにはどうすればよいですか?ベースURLがhttp://192.168.1.64:5050/api/{api_key}であるRequestInterceptorを使用してみましたが、成功しませんでした。

@Override
public void intercept(RequestFacade request) {
    request.addPathParam("api_key", apiKey);
}

他の選択肢はありますか?

23
f2prateek

パス置換は、APIエンドポイントのベースURL内では発生せず、メソッドの相対URL文字列のみで発生します。インターフェースメソッドの宣言すべてに相対URLのプレフィックスを付けたくないと仮定します。

言葉遣いは不十分ですが、 Endpoint のjavadocは次のように述べています。

呼び出し元は、戻り値をキャッシュするのではなく、常に最新の値についてインスタンスを調べる必要があります。

つまり、すべてのリクエストに対して、ベースURLの値についてEndpointインスタンスが調べられます。

APIキー値を変更できるカスタムEndpoint実装を提供できます。

public final class FooEndpoint implements Endpoint {
  private static final String BASE = "http://192.168.1.64:5050/api/";

  private String url;

  public void setApiKey(String apiKey) {
    url = BASE + apiKey;
  }

  @Override public String getName() {
    return "default";
  }

  @Override public String getUrl() {
    if (url == null) throw new IllegalStateException("API key not set.");
    return url;
  }
}
16
Jake Wharton

これを使って:

@PUT("/path1/path2/{userId}")
void getSomething(
        @Path("userId") String userId
);

そしてあなたはこのようにメソッドを呼び出します:

String userId = "1234";
service.getSomething(userId);
32
cgr

パスパラメータが各リクエストのURLの同じ位置にない場合、たとえば、http://endpoint/blah/{apiKey}およびhttp://endpoint/blah/blah/{apiKey}/blah、次のことができます。

APIServiceインターフェース

    @GET(/blah/{apiKey})
    void getFoo(Callback<Object> callback);

    @GET(/blah/blah/{apiKey}/blah)
    void getFooBlah(Callback<Object> callback);

次に、ApiClientクラスにRequestInterceptorを作成します

private static APIService sAuthorizedApiService;
private static Gson gson;

static {
    gson = new GsonBuilder().setPrettyPrinting()
            .create();
}


public static synchronized APIService getApiClient(final Context context) {
    if (sAuthorizedApiService == null) {
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addPathParam("apiKey", DataProvider.getInstance(context).getApiKey();
            }
        };

        RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL)
                .setClient(new OkClient(new OkHttpClient()))
                .setEndpoint("http://endpoint")
                .setRequestInterceptor(requestInterceptor)
                .setConverter(new GsonConverter(gson))
                .build();
        sAuthorizedApiService = restAdapter.create(GMAuthorizedApiService.class);
    }
    return sAuthorizedApiService;
}
3
Jessy Conroy