我在想,使用HttpClient和HttpPOST有沒有辦法將複雜的JSON對象作爲請求的主體?我確實看到了身體張貼一個簡單的鍵/值對的例子(從這個鏈接如下所示:Http Post With Body):HttpPost在請求正文中發佈複雜的JSONObject
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 =新StringEntity(,ContentType.APPLICATION_JSON)' –
sura2k