首页 > 解决方案 > Python 3 请求和标头顺序

问题描述

我想按照我写下来的完全相同的顺序来做一个带有标题的请求。但是通过 Burp,我发现无论我如何在代码中编写它,它似乎都会以另一种方式自行对标头进行排序。

这是我的标题订单:

headers = {
    'Host': 'localhost',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'de-DE',
    'Accept-Encoding': 'gzip, deflate',
    'Content-type': 'application/json',
    'Content-Length': '31',
    'Referer': 'https://localhost',
    'Connection': 'close',
    'Origin': 'https://localhost',
}

这是 Burp 截获的请求中的顺序:

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0
Accept-Encoding: gzip, deflate
Accept: application/json, text/plain, */*
Connection: close
Host: localhost
Accept-Language: de-DE
Content-type: application/json
Content-Length: 32
Referer: https://localhost
Origin: https://localhost

版本和操作系统:

Windows 10 
python3 --version
Python 3.8.6rc1
pip freeze |findstr requests
requests==2.24.0

标签: python-3.xpython-requestshttp-headers

解决方案


我发现最好的方法不是用请求,而是用袜子。Requests Lib 中似乎仍然存在问题。我会将其注册为 github 问题。下面我添加了关于袜子的代码。也许它会帮助某人。

HOST = "XXX.com"
PORT = 443

payload = {"json":"data"}
Length = len(payload.encode())

headers = f"""\
POST / HTTP/1.1\r
Host: XXX.com\r
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0\r
Accept: application/json, text/plain, \r
Accept-Language: de-DE \r
Content-type: application/json \r
Content-Length: {Length} \r
Referer: XXX.com \r
Connection: close \r
Origin: XXX.com \r
\r\n"""

context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_sock = context.wrap_socket(s, server_hostname=HOST)
s_sock.connect((HOST, PORT))
s_sock.send(headers.encode() + json.encode())

while True:
    data = s_sock.recv(2048)
    if ( len(data) < 1 ) :
        print(data.decode())
        break
s_sock.close()

推荐阅读