Skip to main content

RestTemplate : How to get response from a server by HTTP GET call

Points To Remember

You need to add the following dependency to your project to use Spring Rest Template.

compile('org.springframework:spring-web:3.0.2.RELEASE')

How to get response from a server by HTTP GET call

Following are the methods that can be used to get the response from a url using HTTP GET method.
  • getForObject()

    This method takes a URL, Response class (it tells that the response should be bound to this class).
    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.getForObject("http://localhost:8080/someUrl",String.class);

    Following method will make a Http GET call with params.
    Map<String,String> params = new LinkedHashMap<String, String>();
    params.put("userId","1");

    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.getForObject("http://localhost:8080/someUrl",String.class,params);

    This method does not give the following
    • Http status code for the GET call
    • Http headers of the response from the server
    In case you need these headers and status code then you might need to use the getForEntity() or exchange() methods.
  • getForEntity()

    This method can be used to send a HTTP GET request to a url.
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/someUrl",String.class);
    Following method will make a Http GET call with params.
    Map params = new LinkedHashMap();
    params.put("userId","1");

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/someUrl",String.class);

    You can get the response as follows
    • Response Headers : response.getHeaders();
    • Status Code : response.getStatusCode();
    • Response Body : response.getBody();

Comments