gpt4 book ai didi

java - 我应该看到带有文本/纯文本的标题吗?

转载 作者:行者123 更新时间:2023-12-01 13:22:34 24 4
gpt4 key购买 nike

我正在做一个书本上的练习,用 Java 创建一个非常原始的 Web 服务器,只使用 Socket。我相信我一切正常,除了当我将浏览器指向 localhost:8080 时,我看到响应中包含 header 。我的浏览器中的响应如下所示:

HTTP/1.1 200 Ok
content-type: text/plain; charset=UTF-16
content-length: 50
date: Sat, 22 Feb 2014 01:21:50 GMT
Success!! You connected.

我生成响应的代码如下所示:

private static final String HTTP_VALID = "HTTP/1.1";
private static final String METHOD_GET = "GET";
private static final String ENCODING = "UTF-16";
private static final String CONTENT_TYPE = "Content-Type: text/plain; charset=" + ENCODING;
private static final String CONTENT_LENGTH = "Content-Length: ";
private static final String DATE = "Date: ";

private void issueResponse(String dir, boolean success) throws IOException
{
try (BufferedWriter buf = new BufferedWriter
(new OutputStreamWriter(clientSocket.getOutputStream(), ENCODING)))
{
String statusCode = null;
String statusResponse = null;
String message = null;

if (success)
{
statusCode = "200";
statusResponse = "Ok";
message = "Success!! You connected.";
}
else
{
statusCode = "404";
statusResponse = "Not Found";
message = "Failure, resource not found.";
}

long cLength = message.getBytes(ENCODING).length;
int l = message.length();
String now = generateDate();

buf.write(HTTP_VALID + " " + statusCode + " " + statusResponse);
buf.write(System.lineSeparator());
buf.write(CONTENT_TYPE);
buf.write(System.lineSeparator());
buf.write(CONTENT_LENGTH + cLength);
buf.write(System.lineSeparator());
buf.write(DATE + now);
buf.write(System.lineSeparator());
buf.write(System.lineSeparator());
buf.write(message);
buf.flush();
}
}

我应该在浏览器中看到这样的 header ,还是我做错了什么?

更新:这是 telnet session 的结果,标题前似乎有一个垃圾字符,这可能是什么原因造成的?

Steve@Steve-PC ~
$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.1

▒HTTP/1.1 200 Ok
Content-Type: text/plain; charset=UTF-16
Content-Length: 50
Date: Sat, 22 Feb 2014 01:37:56 GMT

Success!! You connected.Connection closed by foreign host.

更新 - 将编码更改为 UTF-8 并且没有垃圾字符,这是什么?

最佳答案

您的文本没有作为标题发送。它是在服务器生成的 header 之后发送的。您可以通过控制台连接到服务器来检查这一点(您也可以使用公开 header 的任何客户端)。

标题有一个强制换行符,表明它已完成。

如果工作正常,如果您通过控制台客户端连接到服务器端口(请注意新行),则输出应该是:

HTTP/1.1 200 Ok
Content-Type: text/plain; charset=UTF-16
Content-Length: 50
Date: Sat, 22 Feb 2014 01:21:50 GMT

Success!! You connected.

关于java - 我应该看到带有文本/纯文本的标题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21948377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com