JAVA:我无法将响应(json)从服务器发送回客户端

JAVA :I'm not able to send response(json) back to the client from server

我有一个客户端应用程序,它向自定义服务器发送 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 服务器,但您的代码中至少存在两个问题:

  1. 您缺少 header 个姓名,例如application/json;charset=UTF-8 应该读作 Content-Type: application/json;charset=UTF-8
  2. out.println() 使用系统 属性 line.separator 定义的行分隔符字符串(例如 \n 代表 Linux)。另一方面,HTTP 需要 \r\n,所以最好这样写: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);