Skip to content

Instantly share code, notes, and snippets.

@junlincao
Created December 15, 2015 16:49
Show Gist options
  • Save junlincao/5065b0d36997d95f4635 to your computer and use it in GitHub Desktop.
Save junlincao/5065b0d36997d95f4635 to your computer and use it in GitHub Desktop.
okhttp Interceptor 中为post等body添加额外字段(MultipartRequestBody 可能有问题,未测试)
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
final Request request = chain.request();
if (!HttpMethod.requiresRequestBody(request.method())) {
return chain.proceed(request);
}
final RequestBody newRb = new FormEncodingBuilder()
.add("testExtra", "123")
.build();
final RequestBody oldBody = request.body();
Request nowReq = request.newBuilder().method(request.method(), new RequestBody() {
@Override
public long contentLength() throws IOException {
if (oldBody.contentLength() <= 0) {
return newRb.contentLength();
}
return oldBody.contentLength() + 1 + newRb.contentLength();
}
@Override
public MediaType contentType() {
return request.body().contentType();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (oldBody.contentLength() > 0) {
request.body().writeTo(sink);
sink.writeByte('&');
}
newRb.writeTo(sink);
}
}).build();
return chain.proceed(nowReq);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment