Python socket和HTTP协议的GET方法?

问题描述 投票:0回答:1

我在使用 获取 HTTP协议的方法,使用 插座 在python 3.8.2中的库。我的代码。

import socket

mysocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysocket.connect(('www.w3.org',80))

msg = 'GET https://www.w3.org/Status.html HTTP/1.1\r\n\r\n'
mysocket.sendall(msg.encode())

while True:
    data = mysocket.recv(1024)
    if (len(data)<1):
        break
    data.rstrip()
    print(data.decode())

mysocket.close()

它应该在控制台中打印出w3.orgStatus.html的html代码,但它却返回了一个 Error 400 Bad Request,在这里。

$ python web_navigator.py

HTTP/1.1 400 Bad Request
date: Thu, 23 Apr 2020 02:13:59 GMT
last-modified: Thu, 26 Mar 2020 19:01:07 GMT
etag: "3f4-5a1c69b70a2c0"
accept-ranges: bytes
content-length: 1012
vary: upgrade-insecure-requests
content-type: text/html; charset=iso-8859-1

在这之后,显示了一个html页面的错误。400

谁能帮我解决这个问题?

python sockets http protocols
1个回答
1
投票

Host强制 对于 HTTP/1.1,并且,当你连接 80 埠,计划应该是 http所以,只要把你的信息改成。

msg = 'GET http://www.w3.org/Status.html HTTP/1.1\r\nHost: www.w3.org\r\n\r\n'
© www.soinside.com 2019 - 2024. All rights reserved.