如何使用 Apache HttpClient POST JSON 请求? [英] How to POST JSON request using Apache HttpClient?

查看:46
本文介绍了如何使用 Apache HttpClient POST JSON 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似以下内容:

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+ 是如何做到的?

It keeps coming back with a 500. The service provider says I need to send JSON. How is that done with Apache HttpClient 3.1+?

推荐答案

Apache HttpClient 对 JSON 一无所知,因此您需要单独构建 JSON.为此,我建议查看来自 JSON-java 库://www.json.org/" rel="noreferrer">json.org.(如果JSON-java"不适合您,json.org 有大量不同语言的库列表.)

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

一旦你生成了你的 JSON,你就可以使用类似下面的代码来发布它

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

编辑

注意 - 如问题中所要求的,上述答案适用于 Apache HttpClient 3.1.但是,为了帮助任何正在寻找针对最新 Apache 客户端的实现的人:

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

这篇关于如何使用 Apache HttpClient POST JSON 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆