在拦截中向请求者改进2个附加帖子

时间:2015-11-06 19:56:51

标签: android retrofit 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);
    }
});

但是还想在包含userkey的请求正文中附加一个post key-value。这看起来像

    RequestBody newBody = RequestBody.create(request.body().contentType(),request.body().content+ request.addPost("sUserKey","3254345kdskf");
...
...
 Request newRequest = chain.request()
.newBuilder()
.url(url)
.post(newBody)
.build();

2 个答案:

答案 0 :(得分:5)

追加RequestBody不是直截了当的。以下是将添加post参数的自定义RequestBody的草图。几点需要注意 - 您需要添加一些错误检查,例如确保现有主体不为空。给定代码还假设所有来到此拦截器的调用都是POST。如果不是这种情况,则在应用新主体之前,您需要检查传入的请求类型。此外,由于这只是将新参数复制到正文中,因此您需要确保名称和正文已根据需要进行了网址编码。

class AddPostParamRequestBody extends RequestBody {

    final RequestBody body;
    final String parameter;

    AddPostParamRequestBody(RequestBody body, String name, String value) {
        this.body = body;
        this.parameter = "&" + name + "=" + value;
    }

    @Override
    public long contentLength() throws IOException {
        return body.contentLength() + parameter.length();
    }

    @Override
    public MediaType contentType() {
        return body.contentType();
    }

    @Override
    public void writeTo(BufferedSink bufferedSink) throws IOException {
        body.writeTo(bufferedSink);
        bufferedSink.writeString(parameter, Charset.forName("UTF-8"));
    }

} 

然后你可以在你的拦截器中使用 -

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("added", "param").build();
        AddPostParamRequestBody newBody = new AddPostParamRequestBody(request.body(), "sUserKey","3254345kdskf");
        Request newRequest = request.newBuilder().post(newBody).url(url).build();
        return chain.proceed(newRequest);
    }
});

您的另一个选择是在您的改装定义中包含额外的Field注释,并在每次通话时传递它,但我认为您试图避免这种情况。

答案 1 :(得分:3)

您可以在不创建其他课程的情况下完成此任务。

client.interceptors().add(new Interceptor() {
    @Override
    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String parameter = "&" + name + "=" + value;
        Request newRequest = interceptRequest(request, parameter)
        return chain.proceed(newRequest);
    }
});

这是创建新请求的简单方法。

 public static Request interceptRequest(@NotNull Request request, @NotNull String parameter)
            throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Sink sink = Okio.sink(baos);
        BufferedSink bufferedSink = Okio.buffer(sink);

        /**
         * Write old params
         * */
        request.body().writeTo(bufferedSink);

        /**
         * write to buffer additional params
         * */
        bufferedSink.writeString(parameter, Charset.defaultCharset());

        RequestBody newRequestBody = RequestBody.create(
                request.body().contentType(),
                bufferedSink.buffer().readUtf8()
        );

        return request.newBuilder().post(newRequestBody).build();
    }

您也可以从Gist

获取