spring-android Rest Template 401 and HttpMessageNotReadableException

175 Views Asked by At

I've set my convertors like so - converters = {StringHttpMessageConverter.class, FormHttpMessageConverter.class, MappingJackson2HttpMessageConverter.class}

I assumed that it would try string first before trying to map to JSON. How do I signal to the underlying converter to not try and map to JSON as this response is a 401 Unauthorized and I would like to try and re-authenticate for my case and attempt the same operation?

Or should I just include a catch block with this specific exception to handle this?

Getting the following exception.

W/System.err: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'Unauthorized': was expecting ('true', 'false' or 'null') W/System.err: at [Source: buffer(com.android.okhttp.internal.http.HttpConnection$FixedLengthSource@f03e4ce).inputStream(); line: 2, column: 14]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Unauthorized': was expecting ('true', 'false' or 'null') W/System.err: at [Source: buffer(com.android.okhttp.internal.http.HttpConnection$FixedLengthSource@f03e4ce).inputStream(); line: 2, column: 14]

1

There are 1 best solutions below

0
Jagadish On

Based on your response i.e 401 which is Unauthorized error response, set the headers to HttpEntity:

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer <token id>");