Why should the RestTemplate GET response in JSON be in XML?

I successfully worked with extrange spring using RestTemplate (org.springframework.web.client.RestTemplate) without success.

I use the code below in my application for the application and always get an XML response, which I parse and evaluate its result.

String apiResponse = getRestTemplate().postForObject(url, body, String.class);

But I can’t understand why the server response is in JSON format after execution:

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

I was debugging on a low-level RestTemplate, and the content type is XML, but I have no idea why the result is in JSON.

When I access from the browser, the response is also in XML, but in apiResponse I got JSON.

I tried many options after reading the spring documentation http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/client/RestTemplate.html

, .

RestTemplate , /json:

public void doWithRequest(ClientHttpRequest request) throws IOException {
            if (responseType != null) {
                List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
                for (HttpMessageConverter<?> messageConverter : getMessageConverters()) {
                    if (messageConverter.canRead(responseType, null)) {
                        List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes();
                        for (MediaType supportedMediaType : supportedMediaTypes) {
                            if (supportedMediaType.getCharSet() != null) {
                                supportedMediaType =
                                        new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype());
                            }
                            allSupportedMediaTypes.add(supportedMediaType);
                        }
                    }
                }
                if (!allSupportedMediaTypes.isEmpty()) {
                    MediaType.sortBySpecificity(allSupportedMediaTypes);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Setting request Accept header to " + allSupportedMediaTypes);
                    }
                    request.getHeaders().setAccept(allSupportedMediaTypes);
                }
            }
        }

?

+4
1

RC. . , .

, Accept APPLICATION/JSON, , Accept, .

:

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

, :

// 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<String> entity = new HttpEntity<String>("parameters", headers);

ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.GET, entity, String.class);
String responseBody = response.getBody();
+8

Source: https://habr.com/ru/post/1525684/


All Articles