Friday, May 18, 2012

using Spring RestTemplate with parameters

I had to use HTTP today to get some data of remote service.
Usually I rather write a servlet on server side, so my first idea was to use simply java.net.URL to perform this task.
First you create URL, then openConnection, then open stream... and so on. Btw. how to issue POST request?
I just thought that it could be useful to use some more specialized API, but is it sensible to include e.g. Apache HttpClient into project just to issue a few simple requests?
And all code around the URL...

Why there is nothing like JdbcTemplate from Spring to operate on Http?
But wait... Let's look perhaps there is something?
Well smart guys from Spring Source already made it - the RestTemplate class.
Tada!
 Now my operation can look like this:
String pong = new RestTemplate().getForObject(address + PING, String.class);
Validate.isTrue(PONG.equals(pong));

And perhaps you may want to use POST with parameters via RestTemplate?
 HttpHeaders  headers = new HttpHeaders();
 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 HttpEntity req = new HttpEntity<>(urlEncodeYourParams(), headers);
 RestTemplate rest = new RestTemplate();
 ResponseEntity result = rest.postForEntity(address, req, String.class);
 System.out.println( result.getBody() );

Really nice.

---Edit:
To
import org.springframework.web.client.RestTemplate
there is needed dependency on right spring project, as there are lot of there I always have problem to pick up the one, which is:

    org.springframework
    spring-web
    4.1.6.RELEASE

No comments:

Post a Comment