Why RestTemplate GET response is in JSON when should be in XML?

后端 未结 1 980
南笙
南笙 2020-12-29 10:54

I struggled with an extrange spring behavior using RestTemplate (org.springframework.web.client.RestTemplate) without success.

I use in my hole application below cod

1条回答
  •  庸人自扰
    2020-12-29 11:21

    I could solve my issue with RC.'s help. I'll post the answer to help other people.

    The problem was that Accept header is automatically set to APPLICATION/JSON so I had to change the way to invoke the service in order to provide the Accept header I want.

    I changed this:

    String response = getRestTemplate().getForObject(url, String.class);
    

    To this in order to make the application work:

    // Set XML content type explicitly to force response in XML (If not spring gets response in JSON)
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    HttpEntity entity = new HttpEntity("parameters", headers);
    
    ResponseEntity response = getRestTemplate().exchange(url, HttpMethod.GET, entity, String.class);
    String responseBody = response.getBody();
    

    0 讨论(0)
提交回复
热议问题