gpt4 book ai didi

authentication - OKHttp Authenticator 401和407以外的自定义http代码

转载 作者:行者123 更新时间:2023-12-04 17:52:59 34 4
gpt4 key购买 nike

我在服务器端实现了 oauth token ,但在无效 token 或 token 过期时,我收到 200 http 状态代码,但在响应正文中我有{"code":"4XX", "data":{"some":"object"}当我尝试读取 interceptor 中的字符串时我得到 okhttp dispatcher java.lang.illegalstateexception closed因为 response.body().string()必须只调用一次。

我也从这里读到 Refreshing OAuth token using Retrofit without modifying all calls我们可以使用 OkHttp Authenticator 类,但它仅适用于 401/407 我还没有尝试过,因为我不会得到这个。有什么方法可以自定义 Authenticator 并在其中处理我们的逻辑。
谢谢

最佳答案

如果可能,请尝试与您的服务器端讨论响应代码。沟通也是一项非常重要的技能。

如果不可能,您可以通过反射手动修改响应代码,它启用 okHttp 身份验证逻辑。

public OkHttpClient getOkHttpClient() {
return new OkHttpClient.Builder()
.authenticator((route, response) -> {
System.out.println("it working");
return null;
})
.addNetworkInterceptor(new UnauthorizedCaseParserInterceptor())
.build();
}


public class UnauthorizedCaseParserInterceptor implements Interceptor {

@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (isUnauthorizedResponse(response)) {
try {
Field codeField = response.getClass().getDeclaredField("code");
codeField.setAccessible(true);
codeField.set(response, HttpURLConnection.HTTP_UNAUTHORIZED);
} catch (Exception e) {
return response;
}
}
return response;
}

private boolean isUnauthorizedResponse(Response response) {
//parse response...
}
}

请仅将此解决方案用作最后的手段。

关于authentication - OKHttp Authenticator 401和407以外的自定义http代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42994353/

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