如何获取使用请求发送到服务器的字节?

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

我需要获取将通过请求模块发送到服务器的字节。我需要获取字节,因为我想通过套接字模块将它们单独发送到特殊服务器。我该怎么做?

示例代码:

import requests

x = requests.get('http://example.com')

# Here I want to get the bytes of the request.
python http python-requests request
1个回答
0
投票

您可以重写

send()
HTTPConnection
方法,如下例所示。

import requests
import urllib3

class DummyConnection(urllib3.connection.HTTPConnection):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.data = []
    def send(self, data):
        self.data.append(data)

def get_request_bytes(session, req):
    req = req.prepare()
    pool = session.get_adapter(req.url).get_connection(req.url)
    conn = DummyConnection(pool.host, pool.port)
    conn.request(req.method, req.url, headers = req.headers)
    return b''.join(conn.data)

session= requests.Session()
req = requests.Request('GET',
    url = 'http://a.b.c',
    headers = {'a': 'b'},
)
print(get_request_bytes(session, req))
© www.soinside.com 2019 - 2024. All rights reserved.