使用python2实现http multipart/form-data数据传输

Python3貌似有比较方便的方式,Python2得自己写点代码。

代码基本上参考了一位仁兄发布在github上的代码,但是找不到他的链接了,对不住。不过他的代码貌似跑不过,我这里做了修改后,发布在这里,希望对后来人有帮助。

其实最重要的还是要了解http有关这部分的协议。不懂的可以找相关资料了解一下,这里推荐一个:

《HTTP协议之multipart/form-data请求分析》

import httplib
import mimetypes


def post_multipart(host, selector, fields, files):
    content_type, body = encode_multipart_formdata(fields, files)
    body_buf = bytearray(body)
    h = httplib.HTTP(host)
    h.putrequest('POST', selector)
    h.putheader('content-type', content_type)
    h.putheader('content-length', str(len(body_buf)))
    h.endheaders()
    h.send(body_buf)
    errcode, errmsg, headers = h.getreply()
    print errcode, errmsg
    return h.file.read()


def encode_multipart_formdata(fields, files):
    LIMIT = '----------lImIt_of_THE_fIle_eW_$'
    body = []
    for (key, value) in fields:
        body.extend(bytes('\r\n--' + LIMIT + '\r\n'))
        body.extend(bytes('Content-Disposition: form-data; name="%s"\r\n' % key))
        body.extend(bytes('\r\n'))
        body.extend(bytes(value))
    for (key, filename, value) in files:
        body.extend(bytes('\r\n--' + LIMIT + '\r\n'))
        body.extend(bytes('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)))
        body.extend(bytes('Content-Type: %s\r\n' % get_content_type(filename)))
        body.extend(bytes('\r\n'))
        body.extend(value)
    body.extend('\r\n--' + LIMIT + '--\r\n')
    content_type = 'multipart/form-data; boundary=%s' % LIMIT
    return content_type, body


def get_content_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'


if "__main__" == __name__:
    data = [0x01, 0x02, 0x03, 0x04]
    fields = [("type", "0")]
    files = [("data", "data", data)]
    response_str = post_multipart("127.0.0.1:8080", "/doSomething", fields, files)
    print response_str


猜你喜欢

转载自blog.csdn.net/K0000000r/article/details/74911083