mlhack
mlhack

Reputation: 73

How to get response object from POST request?

It is a Spring application, I'm trying to make a POST request and get back a response.

At server side I have this

@CrossOrigin
@RequestMapping(value = "/test", method = RequestMethod.POST)
public
@ResponseBody
Test testmethod(@RequestBody Test test) {
    test.setValue("test");
return test;
}

At client side I have the post method which should return the Test object. I use JSON for ecoding.

public Object post(String url1, Test test) throws IOException, ClassNotFoundException {

    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = mapper.writeValueAsString(login);

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url1);

        StringEntity input = new StringEntity(jsonInString);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        //read the object from the response, how to do that?
        //responseObject = ?????

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
return responseObject;
}

And

Test s = new Test;
Test s=(Test)post("http://localhost:8081/basic-web-app/test",s);

My problem is that i don't know hot to get the Test object from the response. Please help. Thanks!

Upvotes: 2

Views: 10558

Answers (1)

mariusz2108
mariusz2108

Reputation: 881

You can try to use:

String responseAsString = EntityUtils.toString(response.getEntity());

Upvotes: 1

Related Questions