小编典典

如何强制http.client在python中发送分块编码的HTTP正文?

python

我想发送分块的HTTP正文以测试我自己的HTTP服务器。所以我写了这个python代码:

import http.client

body = 'Hello World!' * 80

conn = http.client.HTTPConnection("some.domain.com")
url = "/some_path?arg=true_arg"

conn.request("POST", url, body, {"Transfer-Encoding":"chunked"})

resp = conn.getresponse()
print(resp.status, resp.reason)

我希望HTTP请求的主体被传输成块,但是我用Wireshark捕获了网络包,HTTP请求的主体没有被传输成块。

如何通过python中的http.client lib传输分块主体?


阅读 213

收藏
2021-01-20

共1个答案

小编典典

好的我明白了。

首先,编写我自己的分块编码函数。

然后使用putrequest(),putheader(),endheaders()和send()代替request()

import http.client

def chunk_data(data, chunk_size):
    dl = len(data)
    ret = ""
    for i in range(dl // chunk_size):
        ret += "%s\r\n" % (hex(chunk_size)[2:])
        ret += "%s\r\n\r\n" % (data[i * chunk_size : (i + 1) * chunk_size])

    if len(data) % chunk_size != 0:
        ret += "%s\r\n" % (hex(len(data) % chunk_size)[2:])
        ret += "%s\r\n" % (data[-(len(data) % chunk_size):])

    ret += "0\r\n\r\n"
    return ret


conn = http.client.HTTPConnection(host)
url = "/some_path"
conn.putrequest('POST', url)
conn.putheader('Transfer-Encoding', 'chunked')
conn.endheaders()
conn.send(chunk_data(body, size_per_chunk).encode('utf-8'))

resp = conn.getresponse()
print(resp.status, resp.reason)
conn.close()
2021-01-20