Dynamic Paths in Retrofit

后端 未结 3 1476
情书的邮戳
情书的邮戳 2020-12-06 09:18

I\'m trying to access a resource with like http://192.168.1.64:5050/api/{api_key}/updater.info.

How would I dynamically set the api_key par

3条回答
  •  旧时难觅i
    2020-12-06 10:09

    If the path parameter is not in the same position in the url for each request, for example, http://endpoint/blah/{apiKey} and http://endpoint/blah/blah/{apiKey}/blah, you could do the following.

    In your APIService Interface

        @GET(/blah/{apiKey})
        void getFoo(Callback callback);
    
        @GET(/blah/blah/{apiKey}/blah)
        void getFooBlah(Callback callback);
    
    
    

    Then in your ApiClient Class create a 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;
    }
    

    提交回复
    热议问题