gpt4 book ai didi

java - 如何在执行 OkHttp 同步请求时获取 HTTP 响应错误代码

转载 作者:行者123 更新时间:2023-11-30 10:39:07 25 4
gpt4 key购买 nike

我将 OkHttp 与 Retrofit 结合使用来执行同步请求。问题是 OkHttp 抛出异常。我可以改为在拦截器中捕获异常,但响应为空。

我想根据 HTTP 响应代码向用户显示消息。

Response<List<Employee>> owner = null;
Call<List<Employee>> webCall = getWebService().getDeviceOwner("tolower(LoginId) eq tolower(\'" + SharedData.AuthorizationUserName + "\')");
try {
owner = webCall.execute();
if(isHttpResponseSuccess(owner.code())) {
Employee employee = owner.body().get(0);
}
else {
Log.e(TAG_NAME, "GetDeviceOwner() call failed. Http code=" + owner.code() + "/nMessage=" + owner.message());
}
catch (Exception e) {

//Some type of network error. 401, etc? I have no clue.
Log.e(TAG_NAME, "GetDeviceOwner() exception=" + e);
}

客户端拦截器

_okHttpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
@Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Content-Type", "Application/JSON")
.addHeader("Authorization", "Basic " + new String(Base64.encode((SharedData.AuthorizationUserName + ":" + SharedData.AuthorizationPassword).getBytes(), Base64.NO_WRAP)))
.removeHeader("charset")
.build();
okhttp3.Response response = chain.proceed(request);
Log.d(TAG_NAME, "Response code="+ response.code());
Log.d(TAG_NAME, "Response="+ response.toString());
return response;
}
}).addInterceptor(logging).build();

最佳答案

您可以测试此代码,当响应不是 2xx 时,您可以使用 e.getMessage() 获取代码;

_okHttpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
@Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Content-Type", "Application/JSON")
.addHeader("Authorization", "Basic " + new String(Base64.encode((SharedData.AuthorizationUserName + ":" + SharedData.AuthorizationPassword).getBytes(), Base64.NO_WRAP)))
.removeHeader("charset")
.build();
okhttp3.Response response = chain.proceed(request);
if (response.code()/100!=2){
throw new IOException(response.code()+"");
}
Log.d(TAG_NAME, "Response code="+ response.code());
Log.d(TAG_NAME, "Response="+ response.toString());
return response;
}
}).addInterceptor(logging).build();

关于java - 如何在执行 OkHttp 同步请求时获取 HTTP 响应错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39417292/

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