gpt4 book ai didi

android - 改造2 : Modifying request body in OkHttp Interceptor

转载 作者:IT老高 更新时间:2023-10-28 22:21:09 24 4
gpt4 key购买 nike

我在 Android 应用程序中使用带有 OkHttp 客户端的 Retrofit 2 (2.0.0-beta3),到目前为止一切顺利。但目前我正面临 OkHttp 拦截器的问题。我正在与之通信的服务器正在请求正文中获取访问 token ,因此当我拦截添加身份验证 token 的请求或在 Authenticator 的身份验证方法中,当我需要添加更新的身份验证 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();

关于android - 改造2 : Modifying request body in OkHttp Interceptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34791244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com