Search code examples
androidresttemplateandroid-annotations

Rest API - how add custom headers?


I want to make POST request with custom header. I can't find information how to do this using AA Rest API - https://github.com/excilys/androidannotations/wiki/Rest%20API .

Should I use ClientHttpRequestInterceptor, which is used for authenticated requests? https://github.com/excilys/androidannotations/wiki/Authenticated-Rest-Client

Thanks for any help!


Solution

  • There is currently an open issue for this : https://github.com/excilys/androidannotations/issues/323

    For now, the only way to do this is with a custom ClientHttpRequestInterceptor. Here is a little example :

    @EBean
    public class CustomHeaderInterceptor implements ClientHttpRequestInterceptor {
    
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] data, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().add("myHeader", "value");
            return execution.execute(request, data);
        }
    
    }
    

    Then, you need to link it to the restTemplate, like this :

    @EBean
    public class MyService {
    
        @RestService
        RestClient restClient;
    
        @Bean
        MobileParametersInterceptor mobileParametersInterceptor;
    
        @AfterInject
        public void init() {
            List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
            interceptors.add(mobileParametersInterceptor);
            restClient.getRestTemplate().setInterceptors(interceptors);
        }
    
    }