我在Android应用程序中使用Retrofit 2(2.0.0-beta3)和OkHttp客户端,到目前为止一切都很顺利.但目前我正面临着OkHttp Interceptor的问题.我正在与之通信的服务器正在请求主体中访问令牌,因此当我需要添加更新的身份验证令牌时,当我拦截添加身份验证令牌的身份验证或身份验证器的身份验证方法时,我需要为此目的修改请求体.但看起来我只能在标题中添加数据,但不能在正在进行的请求中添加数据.我到目前为止编写的代码如下:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
任何人都可以指出正确的方向,如何修改请求体以添加我的访问令牌(第一次或在令牌刷新后更新)?任何指向正确方向的指针都将受到赞赏.