我在Android应用程序中使用带有OkHttp客户端的Retrofit 2(2.0.0-beta3),到目前为止一切都很好。但目前,我正面临OkHttp拦截器的问题。我正在与之通信的服务器正在请求主体中获取访问 token ,因此当我拦截请求添加身份验证 token 的请求时或在需要添加更新的身份验证 token 的身份验证器的身份验证方法中时,我需要为此修改请求主体。但是看起来我只能在 header 中添加数据,而不能在正在进行的请求正文中添加数据。到目前为止,我编写的代码如下:
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (UserPreferences.ACCESS_TOKEN != null) {
// need to add this access token in request body as encoded form field instead of header
request = request.newBuilder()
.header("access_token", UserPreferences.ACCESS_TOKEN))
.method(request.method(), request.body())
.build();
}
Response response = chain.proceed(request);
return response;
}
});
谁能为我指出正确的方向,如如何修改请求正文以添加我的访问 token (第一次或在 token 刷新后更新)?任何指向正确方向的指针将不胜感激。
最佳答案
我使用它来将post参数添加到现有参数中。
OkHttpClient client = new OkHttpClient.Builder()
.protocols(protocols)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
RequestBody formBody = new FormEncodingBuilder()
.add("email", "Jurassic@Park.com")
.add("tel", "90301171XX")
.build();
String postBodyString = Utils.bodyToString(request.body());
postBodyString += ((postBodyString.length() > 0) ? "&" : "") + Utils.bodyToString(formBody);
request = requestBuilder
.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString))
.build();
return chain.proceed(request);
}
})
.build();
public static String bodyToString(final RequestBody request){
try {
final RequestBody copy = request;
final Buffer buffer = new Buffer();
if(copy != null)
copy.writeTo(buffer);
else
return "";
return buffer.readUtf8();
}
catch (final IOException e) {
return "did not work";
}
}
OkHttp3:
RequestBody formBody = new FormBody.Builder()
.add("email", "Jurassic@Park.com")
.add("tel", "90301171XX")
.build();