Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get STRING response from RestTemplate postForLocation?

Tags:

java

rest

spring

I'm creating a REST Client in Java with RestTemplate from Spring Framework.

Everything is fine until i have to do a post with postForLocation.

The webservice i'm having access return a json with informations about the POST ACTION.

In PHP it's fine but i really don't understand how to do in Java with RestTemplate.

public String doLogin()
    {
        Map<String, String> args = new HashMap<String, String>();

        args.put("email", AUTH_USER);
        args.put("token", AUTH_PASS);

        String result = restTemplate.postForLocation(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);

        return result;
    }

This returns NULL.

With same code but using getForObject (and of course, changing the URL to something right) I have a full response, i.e. this works:

String result = restTemplate.getForObject(url, String.class);

So... how get the RESPONSE from a postForLocation?

Obs.: Sorry if this question is dumb. I'm beginner in Java

like image 746
Alexandre Avatar asked Mar 27 '13 20:03

Alexandre


People also ask

What does RestTemplate return?

RestTemplate Methods postForLocation will do a POST, converting the given object into a HTTP request, and returns the response HTTP Location header where the newly created object can be found.


2 Answers

The postForLocation method returns the value for the Location header. You should use postForObject with the String class, which returns the server's response.

So like this:

String result = restTemplate.postForObject(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);

This will return the response as a string.

like image 134
Piet van Dongen Avatar answered Oct 16 '22 23:10

Piet van Dongen


Thanks to one of answers i've figured out how get the response from a POST with Spring by using the postForObject

String result = restTemplate.postForObject(API_URL + "account/authenticate/?email="+ AUTH_USER +"&token="+ AUTH_PASS, null, String.class);

For some reason i can't use arguments with MAP and have to put them inline in URL. But that's fine for me.

like image 44
Alexandre Avatar answered Oct 16 '22 21:10

Alexandre