这是我的代码:
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/