Reputation: 5495
I'm trying to see whenever I get a response from my API with code 401. But when I do, i get an IOException
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == 401) {
mLoginToken.delete();
Toast.makeText(mApplication.getApplicationContext(), R.string.session_error, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(mApplication.getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mApplication.startActivity(intent);
}
return response;
}
I will get the error java.io.IOException: unexpected end of stream on Connection{ proxy=DIRECT@ hostAddress= cipherSuite=none protocol=http/1.1} (recycle count=0)
At the line
Response response = chain.proceed(request);
How should I get the responses with 401 (unauthorized code) in order to handle this?
Upvotes: 8
Views: 12335
Reputation: 1
val contentType = response.body?.contentType()
val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
val message= response.body?.source()?.readString(charset)
It work for me and for good way
Upvotes: -1
Reputation: 1935
I usually use inteceptors for requests only, and to handle errors set an error handler on the rest adapter builder, see example below:
Note:
cause.getResponse()
may returnnull
yourRestAdapterBuilder.setErrorHandler(new ErrorHandler() {
@Override
public Throwable handleError(RetrofitError cause) {
switch (cause.getResponse().getStatus()) {
case 401:
mLoginToken.delete();
Toast.makeText(mApplication.getApplicationContext(), R.string.session_error, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(mApplication.getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mApplication.startActivity(intent);
default:
// suppress or handle other errors
break;
}
}
})
Upvotes: 6