Python3貌似有比较方便的方式,Python2得自己写点代码。
代码基本上参考了一位仁兄发布在github上的代码,但是找不到他的链接了,对不住。不过他的代码貌似跑不过,我这里做了修改后,发布在这里,希望对后来人有帮助。
其实最重要的还是要了解http有关这部分的协议。不懂的可以找相关资料了解一下,这里推荐一个:
《HTTP协议之multipart/form-data请求分析》
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39import 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('rn--' + LIMIT + 'rn')) body.extend(bytes('Content-Disposition: form-data; name="%s"rn' % key)) body.extend(bytes('rn')) body.extend(bytes(value)) for (key, filename, value) in files: body.extend(bytes('rn--' + LIMIT + 'rn')) body.extend(bytes('Content-Disposition: form-data; name="%s"; filename="%s"rn' % (key, filename))) body.extend(bytes('Content-Type: %srn' % get_content_type(filename))) body.extend(bytes('rn')) body.extend(value) body.extend('rn--' + LIMIT + '--rn') 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
最后
以上就是机智纸鹤最近收集整理的关于使用python2实现http multipart/form-data数据传输的全部内容,更多相关使用python2实现http内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复