如何从POST请求获取响应对象?

时间:2016-04-30 17:29:03

标签: spring apache http post request

这是一个Spring应用程序,我正在尝试发出POST请求并返回响应。

在服务器端,我有这个

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

在客户端,我有post方法,它应该返回Test对象。我使用JSON进行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;
}

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

我的问题是我不知道从响应中获取Test对象。请帮忙。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试使用:

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