【问题标题】:How to get response object from POST request?如何从 POST 请求中获取响应对象?
【发布时间】:2016-08-25 18:37:13
【问题描述】:

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

在服务器端我有这个

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

在客户端,我有 post 方法,它应该返回 Test 对象。我使用 JSON 进行编码。

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 对象。请帮忙。谢谢!

【问题讨论】:

    标签: spring apache http post request


    【解决方案1】:

    你可以尝试使用:

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

    【讨论】:

    • 但是我不需要String,需要Test对象。
    • 你发送 json 所以它是一个字符串。只需使用一些 JSON 到对象转换器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多