【发布时间】:2017-10-27 11:33:27
【问题描述】:
我想知道,使用 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。
提前致谢!
【问题讨论】:
-
试试这个,
StringEntity requestBody = new StringEntity(<JSON_HERE>, ContentType.APPLICATION_JSON)
标签: java httpclient apache-httpclient-4.x apache-commons-httpclient