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

标签 java sockets http web tcp

这是我的代码:

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/

相关文章:

java - SpringBoot 2.0.2.RELEASE 与 amqp 错过指标执行器端点

java - 嵌套 if - else 语句的问题

c - 本地通信 - 127.0.0.1 与 IPC

c++ - Protocol Buffer 和实际传输选项 - 套接字或中间件

java - 如何正确导入类: Http Client from Apache Commons

java - 需要 Player 类中的玩家对象

java - Netty 或 java.net.Socket 用于绿地项目?

Android C2DM - 在 http post 中发送什么?

http - 在浏览器中显示 pdf 文件的 REST Web 服务方法

java - ResponseEntity<T> 和@ResponseBody 有什么区别?