在 Python3 中使用套接字库时出现 404 未找到错误
404 Not found Error while using Socket library in Python3
我正在尝试 运行 Python 3.8 中的以下示例代码:
import socket
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com',80))
# since I need to send bytes and not a str. I add a 'b' literal also tried with encode()
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if (len(data)) < 1:
break
print(data)
mysock.close()
but this is throwing 404 Not found error
b'HTTP/1.1 404 Not Found\r\nServer: nginx\r\nDate: Tue, 02 Nov 2021 04:38:35 GMT\r\nContent-Type: text/html\r\nContent-Length: 146\r\nConnection: close\r\n\r\n<html>\r\n<head><title>404 Not Found</title></head>\r\n<body>\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'
same I tried with urllib, It is working fine
import urllib.request
output= urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')
for line in output:
print(line.strip())
有人知道如何解决这个问题吗?帮我弄清楚我在第一个块代码中哪里出错了..
提前致谢!
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
这不是有效的 HTTP 请求,原因如下:
- 它应该包含绝对路径,而不是绝对路径URL
- 它应该包含一个主机 header。尽管这对于 HTTP/1.0(但对于 HTTP/1.1)来说并不是严格要求的,但通常也是如此
- 行尾必须是
\r\n
而不是 \n
以下作品:
mysock.send(b'GET /code/romeo.txt HTTP/1.0\r\nHost: www.py4inf.com\r\n\r\n')
总的来说:虽然 HTTP 看起来很简单,但实际上并非如此。不要仅仅通过查看一些流量来假设事情是如何工作的,而是要遵循实际的标准。即使它最初似乎适用于特定服务器,但稍后可能会中断。
我正在尝试 运行 Python 3.8 中的以下示例代码:
import socket
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com',80))
# since I need to send bytes and not a str. I add a 'b' literal also tried with encode()
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if (len(data)) < 1:
break
print(data)
mysock.close()
but this is throwing 404 Not found error
b'HTTP/1.1 404 Not Found\r\nServer: nginx\r\nDate: Tue, 02 Nov 2021 04:38:35 GMT\r\nContent-Type: text/html\r\nContent-Length: 146\r\nConnection: close\r\n\r\n<html>\r\n<head><title>404 Not Found</title></head>\r\n<body>\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'
same I tried with urllib, It is working fine
import urllib.request
output= urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')
for line in output:
print(line.strip())
有人知道如何解决这个问题吗?帮我弄清楚我在第一个块代码中哪里出错了.. 提前致谢!
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
这不是有效的 HTTP 请求,原因如下:
- 它应该包含绝对路径,而不是绝对路径URL
- 它应该包含一个主机 header。尽管这对于 HTTP/1.0(但对于 HTTP/1.1)来说并不是严格要求的,但通常也是如此
- 行尾必须是
\r\n
而不是\n
以下作品:
mysock.send(b'GET /code/romeo.txt HTTP/1.0\r\nHost: www.py4inf.com\r\n\r\n')
总的来说:虽然 HTTP 看起来很简单,但实际上并非如此。不要仅仅通过查看一些流量来假设事情是如何工作的,而是要遵循实际的标准。即使它最初似乎适用于特定服务器,但稍后可能会中断。