gpt4 book ai didi

java - 使用 Java 连接到 stackoverflow 后,为什么我会收到错误的主机响应?

转载 作者:行者123 更新时间:2023-12-01 12:26:35 26 4
gpt4 key购买 nike

这是我的代码:

public class TestClass {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("198.252.206.16",80);
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
outToServer.writeBytes("GET http://stackoverflow.com:80 HTTP/1.1\n\nHost: http://stackoverflow.com\n");
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int x;
while((x = inputStreamReader.read()) != -1) {
System.out.print((char) x);
}
}
}

我得到的回应是:

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Date: Thu, 09 Oct 2014 18:47:26 GMT
Content-Length: 334

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>
HTTP/1.0 400 Bad request
Cache-Control: no-cache
Connection: close
Content-Type: text/html

<html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>

我做错了什么?

最佳答案

您将 Host header 作为 GET 请求正文的一部分发送。

outToServer.writeBytes("GET http://stackoverflow.com:80 HTTP/1.1\n\nHost: http://stackoverflow.com\n");
// ^ notice two new lines

所以你的 GET 就像

GET http://stackoverflow.com:80 HTTP/1.1  // << request method and headers

Host: http://stackoverflow.com // << request body

相反,只在其中添加一个新行,并在末尾添加两个

outToServer.writeBytes("GET http://stackoverflow.com:80 HTTP/1.1\nHost: http://stackoverflow.com\n\n");

它是正确的,就像

GET http://stackoverflow.com:80 HTTP/1.1  // << request method and headers
Host: http://stackoverflow.com

关于java - 使用 Java 连接到 stackoverflow 后,为什么我会收到错误的主机响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26285861/

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