有没有办法使用Retrofit 2为每个请求添加查询参数?

时间:2015-10-05 11:58:33

标签: java android retrofit

我需要为Retrofit 2.0.0-beta2库发出的每个请求添加一个查询参数。我找到了this solution用于Retrofit 1.9,但是如何在最新的库版本中添加RequestInterceptor

我的界面:

@GET("user/{id}")
Call<User> getUser(@Path("id")long id);

@GET("users/")
Call<List<User>> getUser();

客户端:

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(CLIENT)  // custom OkHTTP Client
                    .build();
service = retrofit.create(userService.class);

7 个答案:

答案 0 :(得分:101)

为了完整起见,这里是使用OkHttp-Interceptor为每个Retrofit 2.x请求添加参数所需的完整代码:

{
    "data":"date",
    "render": function(data){
        return moment.unix(data).format("DD/MM/YYYY")
    }
}

答案 1 :(得分:7)

现在Retrofit发布了2.0.0版,这是我的解决方案:

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                String uid = "0";
                long timestamp = (int) (Calendar.getInstance().getTimeInMillis() / 1000);
                String signature = MD5Util.crypt(timestamp + "" + uid + MD5_SIGN);
                String base64encode = signature + ":" + timestamp + ":" + uid;
                base64encode = Base64.encodeToString(base64encode.getBytes(), Base64.NO_WRAP | Base64.URL_SAFE);

                Request request = chain.request();
                HttpUrl url = request.url()
                        .newBuilder()
                        .addQueryParameter("pageSize", "2")
                        .addQueryParameter("method", "getAliasList")
                        .build();

                request = request
                        .newBuilder()
                        .addHeader("Authorization", "zui " + base64encode)
                        .addHeader("from_client", "ZuiDeer")
                        .url(url)
                        .build();

                Response response = chain.proceed(request);
                return response;
            }
        }).build();


Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(ApiConstants.API_BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();

mRestfulService = retrofit.create(RestfulService.class);

答案 2 :(得分:4)

您必须从Interceptor切换到OkHttp。创建一个OkHttpClient,将Interceptor添加到其中,并在改造Builder中传递该客户端。

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        ...
    }
});

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("...")
        .client(client)
        .build();

然后,您可以使用chain.request().newBuilder()根据需要调整请求。有关详细信息,请参阅documentation

答案 3 :(得分:3)

Style及更高版本中,您应该使用3.2.0中的addInterceptor()代替。

例如,使用Retrolambda

OkHttpClient.Builder

答案 4 :(得分:1)

在kotlin中,将以下拦截器添加到您在Retrofit构建器中设置的OkHttpClient中:

Retrofit.Builder()
    .baseUrl("...")
    .client(
        OkHttpClient.Builder()
            .addInterceptor { chain ->
                val url = chain
                    .request()
                    .url()
                    .newBuilder()
                    .addQueryParameter("key", "value")
                    .build()
                chain.proceed(chain.request().newBuilder().url(url).build())
            }
            .build()
    )
    .build()
    .create(FooService::class.java)

并且,当然,将OkHttpClient建筑物提取为val或注入依赖项将使其更加模块化和易操作。

答案 5 :(得分:1)

为了更简洁的代码方法,为拦截器链提供一个单独的类,如下所示:

    public class LanguageInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            HttpUrl url = chain.request()
                    .url()
                    .newBuilder()
                    .addQueryParameter("name","value")
                    .build();

            Request request = chain.request()
                    .newBuilder()
                    .url(url)
                    .build();
            Response response = chain.proceed(request);
            return response;
        }
    }

然后在您定义改造实例的类中,使用 .addInterceptor(new LanguageInterceptor()) 向其中添加实例对象,如下所示:

public static Retrofit getClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(new LanguageInterceptor())
                .addInterceptor(interceptor)
                .build();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            Log.e(TAG, "getClient: base url " + retrofit.baseUrl());
        }
        return retrofit;
    }

答案 6 :(得分:0)

许多答案都是相似的,但是我遇到的一个问题是Interceptor内部的函数链接,这使它对我来说失败了。根据链接的视频更改cannot be made directly to a url。相反,必须制作该URL的副本,然后将其重新分配回原始URL,如下所示:

{

public method(){
    final String api_key = "key";

    OkHttpClient client = new OkHttpClient.Builder()
                          .addInterceptor(new Interceptor() {
                              @Override
                              public Response intercept(Chain chain) throws IOException {
                                    Request original = chain.request();
                                    HttpUrl httpUrl = original.url();

                                    HttpUrl newHttpUrl = httpUrl
                                                        .newBuilder()
                                                        .addQueryParameter("api_key", api_key)
                                                        .build();

                                    Request.Builder requestBuilder = original
                                                                 .newBuilder()
                                                             .url(newHttpUrl);

                                    Request request = requestBuilder
                                                      .build();
                                    return chain.proceed(request);
                              }
                          }).build();


    retrofit = new Retrofit.Builder()
            .baseUrl("https://base.url.ext/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

虽然所调用的函数与第一个答案相同,但是此答案将函数调用分区。即,原始URL和新URL都存储在单独的局部变量中。这样可以避免覆盖原始URL,直到您希望OkHttpClient覆盖为止。