0

我在想,使用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

提前感謝!

+0

試試這個,'StringEntity requestBody =新StringEntity(,ContentType.APPLICATION_JSON)' – sura2k

回答

0

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

出於某種原因,這將返回我400,我能得到這個請求,通過郵遞員的工作... :(任何其他想法? – BigBug

+0

當我檢查服務器獲得的身體是什麼,當我這樣做時,它什麼也得不到。但是,當我這樣做的方式我發佈我的問題,並添加垃圾值的BasicNameValuePair,我可以看到服務器將這些值設置爲正文 – BigBug

0

這對我有效!

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

我很高興聽到這個消息!如果您發現我的答案對您有幫助,請隨時接受答案:) –