gpt4 book ai didi

Python 对服务器的错误请求

转载 作者:行者123 更新时间:2023-12-01 08:22:20 25 4
gpt4 key购买 nike

我编写了以下程序来向 Python 添加 HTTP 请求:

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()

这是运行python后的结果。

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.

谁能告诉我如何解决这个问题?

最佳答案

问题是由行结尾引起的。尝试使用 \r\n 而不是 \n:

cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()

此行为在RFC2616中进行了解释。 :

The line terminator for message-header fields is the sequence CRLF. However, we recommend that applications, when parsing such headers, recognize a single LF as a line terminator and ignore the leading CR.

显然,Web 服务器 (Apache/2.4.18 (Ubuntu)) 不遵循上述建议,只接受 CRLF (\r\n) 作为行终结者。

关于Python 对服务器的错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54545119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com