Reputation: 73
I'm using OkHttp with Retrofit to do synchronized requests. The problem is that OkHttp throws an exception. I can catch the exception in the interceptor instead, but the response is null.
I'd like to display messages to the user based on HTTP response codes.
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);
}
Client Interceptor
_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();
Upvotes: 2
Views: 6693
Reputation: 36
u can test this code , when the response isn't 2xx it will worked that u can get the code with 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();
Upvotes: 1
Reputation: 2023
You can use HttpResponse class
HttpResponse httpResponse = client.newCall(request).execute();
httpResponse.getStatusLine().getStatusCode();
If you are using com.squareup.okhttp.Response then you can use the code() method.
Response httpResponse = client.newCall(request).execute();
httpResponse.code();
Upvotes: 0