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

HttpPost Posting Complex JSONObject in the Body of the Request

我想知道,使用 HttpClient 和 HttpPOST 是否有办法 post 一个复杂的 JSON 对象作为请求的主体?我确实在正文中看到了 posting 一个简单的 key/value 对的示例(如下所示 link: ):

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);

但是,我需要 post 如下内容:

{
"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。

提前致谢!

HttpPost.setEntity() 接受 StringEntity which extends AbstractHttpEntity。您可以使用您选择的任何有效 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); 

这对我有用!

HttpClient client= new DefaultHttpClient();
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);