我正在使用 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>
我究竟做錯了什么?
uj5u.com熱心網友回復:
HTTP 1.1 要求您至少隨請求一起發送 Host 標頭。
像這樣的東西可能會起作用:
# ...
cmd = 'GET /romeo.txt HTTP/1.1\r\nHost: data.pr4e.org\r\n\r\n'.encode()
mysock.send(cmd)
# ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/462581.html
