400 错误请求套接字

400 Bad request socket

我正在使用 Coursera 学习网络编程,目前正在尝试使用套接字进行基本练习。这是我的代码:

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET https://data.pr4e.org/romeo.txt HTTP/1.1\r\n\r\n'.encode()
mysock.send(cmd)

while True:
    data=mysock.recv(512)
    if (len(data)<1):
        break
    print(data.decode())
mysock.close()

但是每次我这样做,它都会显示:

HTTP/1.1 400 Bad Request
Date: Wed, 20 Apr 2022 18:54:53 GMT
Server: Apache/2.4.18 (Ubuntu)
Content-Length: 308
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>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at do1.dr-chuck.com Port 80</address>
</body></html>     

我做错了什么?

HTTP 1.1 要求您至少随请求发送一个主机 header。

类似这样的方法可能有效:

# ...
cmd = 'GET /romeo.txt HTTP/1.1\r\nHost: data.pr4e.org\r\n\r\n'.encode()
mysock.send(cmd)
# ...