2012-02-11 26 views
3

我想發送分塊的HTTP正文來測試我自己的HTTP服務器。 所以我寫了這條巨蟒代碼:如何強制http.client在python中發送chunked-encoding HTTP主體?

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請求的身體transferrd分塊, 但我捕獲網絡包使用Wireshark,HTTP請求的身體不轉讓分塊。

如何通過http.client庫在python中傳輸塊狀體?

回答

7

好的,我明白了。

首先,寫我自己的分塊編碼功能。

然後使用putrequest(),putheader(),endheaders()和send(),而不是請求()

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() 
+2

對我的作品蒙山只有一個分離器更好的爲chunk_data(即內第二行:滯留+ =「%S \ r \ n」%(數據[我* chunk_size:(i + 1)* chunk_size])) – 2012-12-19 17:14:55

1

我建議,如果你已經知道你的數據像大小answer因爲您可以設置Content-Length並將其全部發送回去,這就好比您對conn.send的單個呼叫所做的一切。

當你不知道數據有多大時,分塊傳輸編碼是最有用的。動態生成的內容。我已經修改了你的代碼來說明:

import httplib 

def write_chunk(conn, data): 
    conn.send("%s\r\n" % hex(len(data))[2:]) 
    conn.send("%s\r\n" % data) 

def dynamically_generate_data(): 
    for i in range(80): 
     yield "hello world" 

conn = httplib.HTTPConnection("localhost") 
url = "/some_path" 
conn.putrequest('POST', url) 
conn.putheader('Transfer-Encoding', 'chunked') 
conn.endheaders() 

for new_chunk in dynamically_generate_data(): 
    write_chunk(conn, new_chunk) 
conn.send('0\r\n') 

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