How to get STRING response from RestTemplate postF

2019-06-16 03:39发布

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

标签: java spring rest
2条回答
看我几分像从前
2楼-- · 2019-06-16 04:16

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.

查看更多
再贱就再见
3楼-- · 2019-06-16 04:18

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.

查看更多
登录 后发表回答