首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Apache HttpClient发布JSON请求?

如何使用Apache HttpClient发布JSON请求?
EN

Stack Overflow用户
提问于 2012-08-22 00:31:25
回答 1查看 185.8K关注 0票数 102

我有一些类似以下的东西:

代码语言:javascript
复制
final String url = "http://example.com";

final HttpClient httpClient = new HttpClient();
final PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Content-Type", "application/json");
postMethod.addParameters(new NameValuePair[]{
        new NameValuePair("name", "value)
});
httpClient.executeMethod(httpMethod);
postMethod.getResponseBodyAsStream();
postMethod.releaseConnection();

它总是带着500分回来。服务提供商说我需要发送JSON。Apache HttpClient 3.1+是如何做到这一点的?

EN

回答 1

Stack Overflow用户

发布于 2022-01-29 02:33:37

我使用JACKSON库将对象转换为JSON并设置请求主体,如下所示。下面是完整的示例。

代码语言:javascript
复制
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

    HttpPost httpPost = new HttpPost("https://jsonplaceholder.typicode.com/posts");

    Post post = new Post("foo", "bar", 1);
    ObjectWriter ow = new ObjectMapper().writer();
    String strJson = ow.writeValueAsString(post);
    System.out.println(strJson);

    StringEntity strEntity = new StringEntity(strJson, ContentType.APPLICATION_JSON);
    httpPost.setEntity(strEntity);
    httpPost.setHeader("Content-type", "application/json");

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        System.out.println(response.getCode() + " " + response.getReasonPhrase());

        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        System.out.println(result);

        EntityUtils.consume(entity);
    } catch (ParseException e) {
        e.printStackTrace();
    }

} catch (IOException e) {
    System.out.println(e.getMessage());
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12059278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档