Restetemplate GET Request with custom headers

I need to send a GET request with the header: Content-Type: application/camiant-msr-v2.0+xml . I expect an XML response from the server. I tested the request and response with Postman, and everything is fine. But when I try to do this in Spring with a RestTemplate , I always get 400 bad requests. Exceptions to spring are:

 Jul 09, 2016 12:53:38 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [/smp] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 400 Bad Request] with root cause org.springframework.web.client.HttpClientErrorException: 400 Bad Request at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475) 

My code is:

 MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>(); headers.add("Content-Type", "application/camiant-msr-v2.0+xml"); HttpEntity<?> entity = new HttpEntity<Object>(headers); log.debug("request headers: " + entity.getHeaders()); ResponseEntity<String> response = restTemplate.exchange(queryUrl, HttpMethod.GET, entity, String.class); 

The debug message shows the header as {Content-Type=[application/camiant-msr-v2.0+xml]} , which seems to be correct. I wonder what is wrong with my request and if there is a way to see wire requests for debugging.

+1
spring rest resttemplate
source share
2 answers

In fact, the header to be passed should be named Accept , not Content-Type , as it is a GET method. But the API server API somehow says that it expects a Content-Type , and the command-line / Postman API works well on both Content-Type and Accept . I think this is a Java library that prevents the Content-Type header from being passed to GET requests.

0
source share

Possible interpretations 400 : The content type is not valid for the request or the URLs do not match.

In my personal experience, I have a strong feeling that you were messing queryUrl with queryUrl , so for fine-tuning, here I suggest you use the Spring UriComponentsBuilder class.

 UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("data", data); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> response = restTemplate.exchange( builder.build().encode().toUri(), HttpMethod.GET, entity, String.class); 

Please let me know if it still does not work.

+1
source share

All Articles