我写了下面的程序添加一个HTTP请求到Python:
import socket
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org',80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()
mysock.send(cmd)
print('first half done')
while True:
data = mysock.recv(512)
if (len(data) < 1):
break
print(data.decode())
mysock.close()
下面是运行蟒蛇后的结果。
HTTP/1.1 400 Bad Request
Date: Wed, 06 Feb 2019 00:09:46 GMT
Server: Apache/2.4.18 (Ubuntu)
Content-Length: 308
Connection: close
Content-Type: text/html; charset=iso-8859-1
Your browser sent a request that this server could not understand.
谁能告诉我怎么解决这个问题?
该问题是由行尾造成的。相反\n
的,请尝试使用\r\n
:
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
此行为RFC2616解释说:
用于消息的报头字段的行结束是序列CRLF。不过,我们建议应用程序,例如解析头时,识别单一LF作为行终止,而忽略了领先CR。
显然,Web服务器(Apache/2.4.18 (Ubuntu)
)不遵循上述建议,并只接受CRLF(\r\n
)作为行终止。