Created
December 15, 2015 16:49
-
-
Save junlincao/5065b0d36997d95f4635 to your computer and use it in GitHub Desktop.
okhttp Interceptor 中为post等body添加额外字段(MultipartRequestBody 可能有问题,未测试)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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