【问题标题】:How to write answer from server to client (Java, HTML)如何编写从服务器到客户端的答案(Java、HTML)
【发布时间】:2018-04-21 15:10:27
【问题描述】:

我正在编写我的第一个非常简单的 Java 服务器。

在 sendAnswer 方法中,我有 2 种情况: 1 - 如果 URL 有“/s”,我希望用户在浏览器消息页面中看到,然后附加用户的 IP 地址。那么,我的第一个问题是,如何将 thisIp.getHostAddress() 附加到消息中?

第二种情况 - 未找到 - 我希望用户在浏览器页面未找到消息中看到 - 它有效!但不是第一种情况 - 浏览器什么也没显示,我也收到错误 net::ERR_CONTENT_LENGTH_MISMATCH。你能告诉我,哪里出错了吗?

    public void sendAnswer() throws IOException {
        try {
          if(request.getUri().equals("/s")) {
            InetAddress thisIp = InetAddress.getLocalHost();
            System.out.println("IP:"+thisIp.getHostAddress());
            String msg  = "HTTP/1.0 200 OK\r\n" +
                    "Content-Type: text/html\r\n" +
                    "Content-Length: 23\r\n" +
                    "\r\n" +
                    "<h1>Page</h1>";
            output.write(msg.getBytes());
            output.flush();

          }
          else {
            //  not found
            String errorMessage = "HTTP/1.1 404 Page Not Found\r\n" +
              "Content-Type: text/html\r\n" +
              "Content-Length: 23\r\n" +
              "\r\n" +
              "<h1>Page Not Found</h1>";
            output.write(errorMessage.getBytes());
            output.flush();

          }
        }
        catch (Exception e) {
          // thrown if cannot instantiate a File object
          System.out.println(e.toString() );
        }
      }

【问题讨论】:

  • &lt;h1&gt;Page&lt;/h1&gt; 长度似乎约为 10,而不是 23
  • @JacekCz 你的意思是 13 岁吗?
  • @JacekCz 谢谢!它有帮助!

标签: java http server


【解决方案1】:

正如@JacekCz(错误地)指出的那样,您错误地设置了内容长度:

net::ERR_CONTENT_LENGTH_MISMATCH

表示内容长度有误

String msg  = "HTTP/1.0 200 OK\r\n" +
    "Content-Type: text/html\r\n" +
    "Content-Length: 23\r\n" +
     "\r\n" +
     "<h1>Page</h1>";

是错误的,因为您的消息 &lt;h1&gt;Page&lt;/h1&gt; 的长度为 13,而不是 23(也不是 10,就像 @JacekCz 评论的那样)。

通常,我们问题的答案在于错误代码本身。请务必在询问之前先阅读错误消息:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多