【问题标题】:HttpPost Posting Complex JSONObject in the Body of the RequestHttpPost 在请求正文中发布复杂的 JSONObject
【发布时间】: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(&lt;JSON_HERE&gt;, ContentType.APPLICATION_JSON)

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


【解决方案1】:

HttpPost.setEntity() 接受 StringEntity 扩展 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); 

【讨论】:

  • 出于某种原因,这返回了 400,我可以通过邮递员让这个请求工作...... :( 还有其他想法吗?
  • 当我检查服务器作为主体得到什么时,当我这样做时它什么也得不到。但是,当我按照我在问题中发布的方式进行操作并将垃圾值添加到 BasicNameValuePair 时,我可以看到服务器将这些值设置为正文
【解决方案2】:

这对我有用!

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

【讨论】:

  • 我很高兴听到这个消息!如果您发现我的回答对您有帮助,请随时接受答案:)
猜你喜欢
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 2020-12-13
  • 1970-01-01
相关资源
最近更新 更多