我正嘗試將JSON對象發送到自定義端口上的服務器。然而,我從來沒有從服務器得到任何迴應。我認爲錯誤可能在字符串實體中,但我無法弄清楚它是什麼。無法將JSON發佈到使用Java的HTTP客戶端的服務器
我有一個看看這些其他問題:
How to build a http post request with the correct entity with Java and not using any library?
How to POST data in Android to server in JSON format?
他們都沒有解決我的問題。我試圖從「在Java中使用JSON的HTTP POST」的解決方案(16票),但它不會工作。
這裏是我的代碼:
public void reset() {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
System.out.println("Start");
jsonURL = "http://x.x.x.x:3994";
HttpPost request = new HttpPost(jsonURL);
StringEntity params = new StringEntity("{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}");
request.addHeader("Content-Type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
System.out.println("End");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
控制檯打印「開始」就開始,但我從來沒有從「結束」,也不是來自任何異常堆棧跟蹤任何輸出時。調試程序停止在「httpClient.execute(request)
」行時,並且永遠不會繼續。
當我運行從我的終端的命令:
echo '{"id":1, "method":"object.deleteAll", "params":["subscriber"]} ' | nc x.x.x.x 3994
一切都正確執行,並且我的請求由服務器接收。
我認爲我的問題可能與StringEntity
但我不確定。
編輯:
使用Wireshark的,我能夠捕捉到該數據包被髮送到服務器:
POST/HTTP/1.1 Content-Type: application/json Content-Length: 60
Host: x.x.x.x:3994 Connection: Keep-Alive User-Agent:
Apache-HttpClient/4.2.1 (java 1.5)
{"id":1,"method":"object.deleteAll","params":["subscriber"]}
,這包從服務器回來:
{"id":null,"error":{"code":-32700,"message":"Unexpected character ('P' (code 80)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')"}}
{"id":null,"error":{"code":-32700,"message":"Unexpected character ('c' (code 99)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')"}}
{"id":null,"error":{"code":-32700,"message":"Unexpected character ('C' (code 67)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')"}}
{"id":null,"error":{"code":-32700,"message":"Unexpected character ('C' (code 67)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')"}}
{"id":null,"error":{"code":-32700,"message":"Unexpected character ('H' (code 72)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')"}}
{"id":null,"error":{"code":-32700,"message":"Unexpected character ('C' (code 67)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')"}}
{"id":null,"error":{"code":-32700,"message":"Unexpected character ('U' (code 85)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')"}}
{"id":null,"error":{"code":-32700,"message":"Line must contain a JSON object"}}
你的'Content-Type'應該是'application/json',而不是'application/x-www-form-urlencoded'。 – Perception 2013-02-08 14:34:17
謝謝,試過改變,仍然不工作:( – span 2013-02-08 14:35:57
看起來像這個問題可能在你的服務器端,如果確實有那些痕跡來自那裏。你應該在REST控制檯中嘗試你的請求,並比較設置的頭這個工具與你在代碼中使用的工具一樣 – Perception 2013-02-08 14:51:08