我正在尝试将 JSON 对象发送到自定义端口上的服务器。但是,我从来没有从服务器得到任何响应。我认为错误可能在字符串实体中,但我无法弄清楚它是什么。
我已经看过这些其他问题:
如何使用 Java 构建具有正确实体且不使用任何库的 http post 请求?
如何以 JSON 格式将 Android 中的数据发布到服务器?
他们都没有解决我的问题。我正在尝试“HTTP POST using JSON in Java”中的解决方案(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"}}