39

How can I get the raw json string from spring rest template? I have tried following code but it returns me json without quotes which causes other issues, how can i get the json as is.

ResponseEntity<Object> response  = restTemplate.getForEntity(url, Object.class);
String json = response.getBody().toString();
suraj bahl
  • 2,864
  • 6
  • 31
  • 42

2 Answers2

61

You don't even need ResponseEntitys! Just use getForObject with a String.class like:

final RestTemplate restTemplate = new RestTemplate();
final String response = restTemplate.getForObject("https://httpbin.org/ip", String.class);

System.out.println(response);

It will print something like:

{
  "origin": "1.2.3.4"
}
madhead
  • 31,729
  • 16
  • 153
  • 201
  • My return type is object and I want the raw json string? – Brooklyn99 Nov 24 '20 at 21:54
  • 14
    this won't wotk when the server sends `application/json` as content type `Cannot deserialize instance of java.lang.String out of START_ARRAY token` it will only gibt you a string if the body just contains a json-string – wutzebaer Jan 05 '21 at 08:40
0

You can also use restTemplate.execute and pass ResponseExtractor that just parses the InputStream from the body.

public <T> T execute(String url,
    org.springframework.http.HttpMethod method,
    org.springframework.web.client.RequestCallback requestCallback,
    org.springframework.web.client.ResponseExtractor<T> responseExtractor,
    Object... uriVariables )

For example:

String rawJson = restTemplate.execute(url, HttpMethod.GET, (clientHttpRequest) -> {}, this::responseExtractor, uriVariables);

// response extractor would be something like this
private String responseExtractor(ClientHttpResponse response) throws IOException {
    InputStream inputStream = response.getBody();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    for (int length; (length = inputStream.read(buffer)) != -1; ) {
        result.write(buffer, 0, length);
    }
    return result.toString("UTF-8");
}

This also bypasses ObjectMapper if your using Jackson and stringify invalid JSON.

Don
  • 71
  • 1
  • 4