Set headers using spring android resttemplate and android annotations

I am currently playing with Spring Android Resttemplate to interact with the REST API supported by java. In fact, I use android androids to send http calls to this internal service, and I have to say that these are rocks. Basically, Android annotations allow you to define the interface for service calls and the http methods that will be used for every available api call: it will generate all boiler plate code related to low-level materials, for example, marshalling / unmarshalling, calling the right http as defined interface.

Now I would like to set some headers for http requests: How can I achieve this, knowing that I only have a link to the service interface that defines all the calls? I can also reference the RestTemplate object, but it seems that there is now a way to customize the headers.

any help would be really appreciated thanks

+4
source share
1 answer

I approached him by creating an ApiClient instance in the application class and installing a custom REST template.

In my case, I used Json message conversion for Jackson:

 RestTemplate restTemplate = new RestTemplate(fac); MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter(); converter.getObjectMapper().configure(Feature.UNWRAP_ROOT_VALUE, true); restTemplate .getMessageConverters() .add(converter); mClient.setRestTemplate(restTemplate); 

My factory fac query is as follows:

 ClientHttpRequestFactory fac = new HttpComponentsClientHttpRequestFactory() { @Override protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) { HttpUriRequest uriRequest = super.createHttpRequest(httpMethod, uri); // Add request headers uriRequest.addHeader( "Content-Type", MediaType.APPLICATION_JSON_VALUE); return uriRequest; } @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { if (Config.DEBUG_REQUESTS) { Log.d(TAG, uri); } return super.createRequest(uri, httpMethod); } }; 

A WARNING

Although this works on all Android devices in our office, I recently discovered that headers do not appear with all devices! I'm not sure why this (or the device), but I search in it and try to update this answer when I find permission.

+3
source

All Articles