改造2 addQueryParam替换

时间:2015-11-06 02:14:56

标签: android http post retrofit

在之前的改造版本中,可以添加拦截器并使用它来添加全局需要的查询参数,例如:

 .setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade requestFacade) {
                        requestFacade.addQueryParam("platform", "android");
                        requestFacade.addQueryParam("app_version", com.package.BuildConfig.VERSION_NAME);


                }
            })

使用新的实现,它要求您使用OkHttpClient.interceptors。使用这种新方法,如何在不删除原始参数的情况下附加参数?

2 个答案:

答案 0 :(得分:4)

这是一个okhttp实现 -

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
    @Override
    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.httpUrl().newBuilder()
                     .addQueryParameter("platform", "android")
                     .addQueryParameter("app_version", com.package.BuildConfig.VERSION_NAME)
                     .build();
        Request newRequest = chain.request().newBuilder().url(url).build();
        return chain.proceed(newRequest);
    }
});

将客户端添加到您的改造中 -

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://www.example.com")
    .client(client)         
    .build();

答案 1 :(得分:3)

使用retrofix 2.3.0可以使用以下代码:

final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
    @Override
    public Response intercept(final Chain chain) throws IOException 
    {
        final Request request = chain.request();
        final HttpUrl url = chain.request().url().newBuilder()
             .addQueryParameter("platform", "android")
             .addQueryParameter("app_version", com.package.BuildConfig.VERSION_NAME)
             .build();
        final Request newRequest = chain.request().newBuilder().url(url).build();
        return chain.proceed(newRequest);
    }
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://www.example.com")
    .client(client)         
    .build();