Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 761
suraj bahl Avatar asked Nov 03 '17 20:11

suraj bahl


People also ask

How do I get raw JSON data from REST API?

To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.

What is difference between getForObject and getForEntity?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.


1 Answers

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" } 
like image 165
madhead - StandWithUkraine Avatar answered Sep 30 '22 10:09

madhead - StandWithUkraine