在拦截中对请求主体进行改造2附加帖子 [英] Retrofit 2 appending post to requestbody in intercept
本文介绍了在拦截中对请求主体进行改造2附加帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
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);
}
});
,但还希望将一个附加的后置键值附加到包含用户键的请求正文中.看起来像
but would also like to append an additional post key-value to the request body containing the userkey. This would look something like
RequestBody newBody = RequestBody.create(request.body().contentType(),request.body().content+ request.addPost("sUserKey","3254345kdskf");
...
...
Request newRequest = chain.request()
.newBuilder()
.url(url)
.post(newBody)
.build();
推荐答案
您可以执行此操作而无需创建其他类.
You can do it without creating additional class.
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);
}
});
这是创建新请求的简单方法.
This is simple method that create new request.
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();
}
您还可以从要点
这篇关于在拦截中对请求主体进行改造2附加帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文