使用Java从HTTP请求中获取400错误请求

时间:2020-05-04 08:25:31

标签: java html bad-request

我正在Mac上使用IntelliJ遵循https://www.codejava.net/java-se/networking/java-socket-client-examples-tcp-ip中的“ 4. Java套接字客户端示例:HTTP客户端”指令。

Http配置非常简单:

            PrintWriter writer = new PrintWriter(output, true);

            writer.println("HEAD " + url.getPath() + " HTTP/1.1");
            writer.println("Host: " + hostname);
            writer.println("User-Agent: Simple Http Client");
            writer.println("Accept: text/html");
            writer.println("Accept-Language: en-US");
            writer.println("Connection: close");
            writer.println();

我复制了代码,而IntelliJ中没有任何更改,以测试代码如何工作。但是,按照指示执行“ java HttpClient.java”和“ java HttpClient http://www.codejava.net/java-core”之后,得到的是:

HTTP/1.1 400 Bad Request
Date: Mon, 04 May 2020 07:51:30 GMT
Server: Apache
Content-Length: 420
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<p>Additionally, a 400 Bad Request
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache Server at gator3107.hostgator.com Port 80</address>
</body></html>

我尝试了许多解决方案,但没有一个对我有用。我发现的唯一问题是使用Java 11版编译的HttpClient.class缺少

writer.println("HEAD " + url.getPath() + " HTTP/1.1");
writer.println("Host: " + hostname);

然后我将Java版本更改为1.8,它添加了缺少的行,但是错误没有改变。有趣的是,我的一个朋友在Windows中执行相同的操作得到了预期的一切。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

问题是Windows和Mac上如何打印新行,Windows将新行视为2个字符,CR-回车符(“ \ r”)+ LF-换行符(“ \ n”)"\r\n" ,Mac仅将新行打印为LF("\n")。 HTTP请求期望每行用CRLF "\r\n"分隔,您要打印的代码在Mac上仅为"\n",在Windows上仅为"\r\n",这就是为什么它在Windows平台上可以正常工作的原因。 / p>

要使其在Windows和Mac上均可使用,请尝试以下代码:

            PrintWriter writer = new PrintWriter(output, true);

        writer.print("HEAD " + url.getPath() + " HTTP/1.1\r\n");
        writer.print("Host: " + hostname+"\r\n");
        writer.print("User-Agent: Simple Http Client\r\n");
        writer.print("Accept: text/html\r\n");
        writer.print("Accept-Language: en-US\r\n");
        writer.print("Connection: close\r\n");
        writer.print("\r\n");