我有一个客户端应用程序,它将 POST 请求(json)发送到自定义服务器。服务器必须向传入消息发送响应(json),但我没有在客户端检测到任何响应。
问题不在客户端,因为如果它向另一台服务器发送请求,几秒钟后它会收到响应,我在日志中看到它。
服务器代码
try{
server = new ServerSocket(4321);
client = server.accept();
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
System.out.println("Connection received from " + client.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String s = "SERVER: Started.";
Gson gson = new Gson();
String json = gson.toJson(jsonObject.toString());
while ((s = in.readLine()) != null) {
System.out.println("RECV: "+s);
ss = s.split("PUSH\\s");
out.println("HTTP/1.1 200 OK");
out.println("application/json;charset=UTF-8");
out.println("application/json;charset=UTF-8");
out.println("Jersey/2.27 (HttpUrlConnection 1.8.0_291)");
out.println("no-cache");
out.println("no-cache");
out.println("hostname:4321");
out.println("keep-alive");
out.println("392");
out.println("\n");
out.println(json);
} catch(Exception e) {e.printStackTrace();}
我认为我的问题的根源是 out.println()。我不知道服务器应该向客户端发送什么。响应必须包含 json!
另外,我没有客户端代码。
你能帮忙吗?
虽然我绝对不建议以这种方式编写 HTTP 服务器,但您的代码中至少存在两个问题:
application/json;charset=UTF-8
应该阅读Content-Type: application/json;charset=UTF-8
out.println()
使用由系统属性定义的行分隔符字符串line.separator
(例如\n
对于 Linux)。另一方面\r\n
,HTTP 需要,所以最好这样写:out.print("HTTP/1.1 200 OK\r\n");
尝试这个:
out.print("HTTP/1.1 200 OK" + "\r\n");
out.print("Content-Type: application/json" + "\r\n");
// you shouldn't need the other headers…
out.print("\r\n");
out.print(json);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句