我应该看到带有text / plain的标题吗?

时间:2014-02-22 01:24:16

标签: java http webserver browser

我正在做一本书,用Java创建一个非常原始的Web服务器,只使用Socket。我相信我已经完成了所有工作,除了当我将浏览器指向localhost时:8080我看到响应中包含了标题。我的浏览器中的响应如下所示:

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();
    }
}

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

更新: 这是telnet会话的结果,看起来在标题之前有一个垃圾字符,可能是什么导致这个?

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并且没有垃圾字符,是什么给出的?

1 个答案:

答案 0 :(得分:1)

您的文字未作为标题发送。正在向after发送由服务器生成的标头。您可以通过控制台连接到服务器来检查(您也可以使用任何公开标头的客户端)。

标题有一条强制性换行符,表示已完成。

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

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.