suraj bahl
suraj bahl

Reputation: 3296

Spring restTemplate get raw json string

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();

Upvotes: 40

Views: 65489

Answers (2)

Don
Don

Reputation: 91

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.

Upvotes: 1

madhead
madhead

Reputation: 33374

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"
}

Upvotes: 67

Related Questions