Search code examples
androidspringresterror-handlingandroid-annotations

How do I get the headers from a HttpResponse with Spring resttemplate and androidannotations in case of an Error?


How do I get the headers from a HttpResponse with Spring resttemplate and androidannotations in case of an Error?

I know how to get them in case of no error but I need them in the errorcase because the api I want to use sends a minorstatuscode to clearify the httpstatuscode.


Solution

  • Basically I found a solution.

    The RestClient

    @Rest(rootUrl = "https://proji.at/japi/v1", converters = { MappingJackson2HttpMessageConverter.class }, interceptors = { HttpBasicAuthenticatorInterceptor.class })
    public interface ProjiRestClient extends RestClientErrorHandling {
        RestTemplate getRestTemplate();
    }
    

    The ErrorHandler:

    @EBean
    public class ProjiResponseErrorHandler implements ResponseErrorHandler {
        private static final String TAG = "ProjiResponseErrorHandler";
    
        @Override
        public void handleError(ClientHttpResponse response) throws     IOException {
            int minor = 0;
            try {
                minor = Integer.parseInt(response.getHeaders().    getFirst("minor"));
            } catch (Exception e) {
                // TODO: handle exception
            }
            Log.i(TAG, "Response statuscode: " + response.getStatusCode() +     " minor: "
                    + response.getHeaders().getFirst("minor"));
    
            throw new HttpMethodException(response.getStatusCode().value(),     minor);
        }
    
        @Override
        public boolean hasError(ClientHttpResponse response) throws     IOException {
    
            Log.i(TAG, "Response statuscode: " + response.getStatusCode());
            if (response.getStatusCode().value() >= 400) {
                return true;
            }
            return false;
        }
    
    }
    

    The Fragment that uses the RestClient:

    @RestService
    ProjiRestClient restClient;
    @Bean
    ProjiResponseErrorHandler projiErrorhandler;
    
    @AfterInject
    void afterInject() {
        restClient.getRestTemplate().setErrorHandler(projiErrorhandler);
    }
    

    And off you go calling methods from the restClient.

    ResponseEntity<User> respone = restClient.getAuth(auth);
    

    If anyone knows a better solution, I'd be pleased to hear from it.