I am learning Network programming with Coursera and currently trying to do a basic exercise with socket. This is my code:
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()
But every time I do it, it shows this:
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>
What am I doing wrong?
CodePudding user response:
HTTP 1.1 requires that you at least send a Host header along with your request.
Something like this may work:
# ...
cmd = 'GET /romeo.txt HTTP/1.1\r\nHost: data.pr4e.org\r\n\r\n'.encode()
mysock.send(cmd)
# ...