HttpPost在请求正文中发布复杂JSONObject

时间:2017-05-26 14:15:49

标签: java httpclient apache-httpclient-4.x apache-commons-httpclient

我想知道,使用HttpClient和HttpPOST有没有办法发布一个复杂的JSON对象作为请求的主体?我确实看到了一个在正文中发布简单键/值对的示例(如下所示:Http Post With Body):

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));

request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);

但是,我需要发布如下内容:

{
"value": 
    {
        "id": "12345",
        "type": "weird",
    }
}

我有办法实现这个目标吗?

其他信息

执行以下操作:

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request); 

导致服务器上出现空体...因此我得到了400。

提前致谢!

2 个答案:

答案 0 :(得分:2)

HttpPost.setEntity()接受扩展StringEntityAbstractHttpEntity。您可以使用您选择的任何有效String进行设置:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";

StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());

request.setEntity(entity);
request.setHeader("Content-type", "application/json");

HttpResponse resp = client.execute(request); 

答案 1 :(得分:0)

这对我有用!

BasicObject