我在Android应用程序中使用OkHttp客户端进行Retrofit 2(2.0.0-beta3),至此一切进展顺利。但是目前我正面临着OkHttp拦截器的问题。我与之通信的服务器是在请求体中使用访问令牌,所以当我需要添加auth令牌时,我拦截添加auth令牌的请求或Authenticator的身份验证方法时,需要修改此请求的主体。但它看起来像我只能在标题中添加数据,而不是在正在进行的请求中添加数据。到目前为止,我写的代码如下:Retrofit2:修改OkHttp拦截器中的请求体
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;
}
});
任何人都可以点我朝着正确的方向如何修改请求身体补充我的访问令牌(首次或令牌刷新后更新)?任何指向正确的方向将不胜感激。
这将是一个好主意,关闭缓存在'bodyToString()'返回 –
@ 3K那不是需要之前,缓冲犯规分配任何可以在构造函数中被关闭。 https://github.com/square/okio/blob/master/okio/src/main/java/okio/Buffer.java#L59 – Fabian