繁体   English   中英

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. 您缺少标题名称,例如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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM