【问题标题】:How to put json in HTTPPostRequest Body and then on response reading the body如何将 json 放入 HTTPPost 请求正文中,然后响应读取正文
【发布时间】:2016-09-05 09:11:51
【问题描述】:

我正在尝试使用正文进行 HTTP 发布请求。我想知道如何将 json 对象放入请求正文中,然后读取正文作为响应。

HttpClient httpClient = HttpClientBuilder.create().build();
    String responseString = null;
    try {
        HttpPost request = new HttpPost(link);
        log.info("Executing request " + request.getRequestLine());
        StringEntity params = new StringEntity(data);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        log.info("Exception thrown while executing HTTPPostRequest");
    }
    return responseString;

这是我目前用来发出请求的代码片段。如果使用“StringEntity”是将数据放入正文中的正确选择。 我得到了空的正文,它应该返回包含 json 数据的正文

【问题讨论】:

标签: java post http-post


【解决方案1】:

只要你的“数据”是 json 就可以了。

HttpClient httpClient = HttpClientBuilder.create().build();
    String responseString = null;
    try {
        HttpPost request = new HttpPost(link);
        log.info("Executing request " + request.getRequestLine());
        StringEntity content = new StringEntity(data);
        content.setContentType("application/json"); 
        //or request.setHeader("Content-type", "application/json");
        request.setEntity(content);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        log.info("Exception thrown while executing HTTPPostRequest");
    }
    return responseString;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2017-11-25
    • 1970-01-01
    • 2022-01-24
    • 2021-01-04
    相关资源
    最近更新 更多