2013-07-15 2 views
3

청크 인코딩 된 데이터를 httpbin.org/post에 POST하려고합니다. 내가 Wireshark를 추적을 분석 할 때마다, 나는 여러 덩어리가 전송되는 보이지 않는 두 경우 모두 HTTPLIB 청크로 인코딩 된 데이터를 파이썬에서 POST하는 방법

#!/usr/bin/env python 

import httplib 
import os.path 

if __name__ == "__main__": 
     conn = httplib.HTTPConnection('httpbin.org') 
     conn.connect() 
     conn.putrequest('POST', '/post') 
     conn.putheader('Transfer-Encoding', 'chunked') 
     conn.putheader('Connection', 'Keep-Alive') 
     conn.putheader('Cache-Control', 'no-cache') 
     conn.endheaders() 
     for i in range(130): 
       conn.send(str(i)) 

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

를 사용하여 요청

#!/usr/bin/env python 

import requests 

def gen(): 
     l = range(130) 
     for i in l: 
       yield '%d' % i 

if __name__ == "__main__": 
     url = 'http://httpbin.org/post' 
     headers = { 
         'Transfer-encoding':'chunked', 
         'Cache-Control': 'no-cache', 
         'Connection': 'Keep-Alive', 
         #'User-Agent': 'ExpressionEncoder' 
       } 
     r = requests.post(url, headers = headers, data = gen()) 
     print r 

를 사용하여 요청 및 HTTPLIB

: 나는 두 가지 옵션을 시도 . 대신, 모든 데이터가 단일 청크로 전송된다는 것을 알 수 있습니까? 내가 여기서 뭔가를 놓치고 있니?

+0

[HTTP.client가 청크로 인코딩 된 HTTP 본문을 python으로 보내려면 어떻게해야합니까?] (http://stackoverflow.com/q/9237961/95735) –

+2

정말입니까? Wireshark에서 단일 HTTP 메시지를 선택하면 HTTP (Hypertext Transfer Protocol) 부분을 확장 할 수 있습니다. 확장 된 부분에는 데이터가 포함 된 'HTTP 청크 응답'이라는 하위 제목이 있어야합니다. – Lukasa

+1

@ 루카사 : 네, 맞습니다. 어떤 이유로 Wireshark에 청크 데이터가 나타나는 지에 대한 나의 이해가 결함이었습니다. 나는 항상 그것이 분리 된 패킷으로 보인다고 생각했다. 시간 내 줘서 고마워. httplib를 사용하는 –

답변

2

게시 한 코드가 올바르게 작동하지 않아야합니다. httpbin.org가 현재 청크 분할 전송 인코딩을 지원하지 않기 때문에 여전히 성공적인 응답을 얻는 이유가 있습니다. 버그 https://github.com/kennethreitz/httpbin/issues/102을 참조하십시오.

위의 게시물 Piotr과 마찬가지로 각 청크의 길이를 16 진수로 작성한 다음 청크 자체를 작성해야합니다.

예를 들어 코드를 작성했습니다. http://httpbin.org/post 끝 점이 a form that you can use for testing입니다. 그것이 내가 chunk1chunk2 양식 데이터를 생성 한 곳입니다.

POST /post HTTP/1.1 
Host: httpbin.org 
Accept-Encoding: identity 
Transfer-Encoding: chunked 
Content-Type: application/x-www-form-urlencoded 

37 
custname=bob&custtel=11111&custemail=bob%40email.com&si 
51 
ze=medium&topping=bacon&delivery=11%3A00&comments=if+you%27re+late+we+get+it+free 
HTTP/1.1 200 OK 
Connection: close 
Server: gunicorn/18.0 
Date: Fri, 31 Oct 2014 10:37:24 GMT 
Content-Type: application/json 
Content-Length: 494 
Access-Control-Allow-Origin: * 
Access-Control-Allow-Credentials: true 
Via: 1.1 vegur 

{ 
    "args": {}, 
    "data": "", 
    "files": {}, 
    "form": {}, 
    "headers": { 
    "Accept-Encoding": "identity", 
    "Connect-Time": "2", 
    "Connection": "close", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "Total-Route-Time": "0", 
    "Transfer-Encoding": "chunked", 
    "Via": "1.1 vegur", 
    "X-Request-Id": "5053a365-ca6a-4c29-b97a-f7a6ded7f2d9" 
    }, 
    "json": null, 
    "origin": "110.174.97.16", 
    "url": "http://httpbin.org/post" 
}0 
:

import httplib 
import time 

chunk1 = "custname=bob&custtel=11111&custemail=bob%40email.com&si" 
chunk2 = "ze=medium&topping=bacon&delivery=11%3A00&comments=if+you%27re+late+we+get+it+free" 

if __name__ == "__main__": 
    conn = httplib.HTTPConnection('httpbin.org') 
    conn.connect() 
    conn.putrequest('POST', '/post') 
    conn.putheader('Transfer-Encoding', 'chunked') 
    conn.putheader('Content-Type', 'application/x-www-form-urlencoded') 
    conn.endheaders() 

    conn.send("%s\r\n" % hex(len(chunk1))[2:]) 
    conn.send("%s\r\n" % chunk1) 

    time.sleep(1) 

    conn.send("%s\r\n" % hex(len(chunk2))[2:]) 
    conn.send("%s\r\n" % chunk2) 

    time.sleep(1) 
    /* last chunk */ 
    conn.send("0\r\n\r\n") 

    r = conn.getresponse() 
    print r.status, r.reason, r.read() 

와이어 샤크의 스트림은 (후행 0 통지) 기다리거나 우리가 보낸 요청 본문합니다 (json: null 통지를) 해석 아니에요으로 잘못 다음과 같을 것