您的位置:首页 > 编程语言 > Python开发

使用python的requests 发送multipart/form-data 请求

2015-02-06 09:54 1141 查看
网上关于使用python 的发送multipart/form-data的方法,多半是采用

ulrlib2 的模拟post方法,如下:

import urllib2

boundary='-------------------------7df3069603d6'
data=[]
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="app_id"\r\n')
data.append('xxxxxx')
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="version"\r\n')
data.append('xxxxx')
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="platform"\r\n')
data.append('xxxxx')
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="libzip"; filename="C:\Users\danwang3\Desktop\libmsc.zip"')
data.append('Content-Type: application/octet-stream\r\n')

fr=open('C:\Users\danwang3\Desktop\libmsc.zip')
content=fr.read()
data.append(content)
print content
fr.close()
data.append('--%s--\r\n'%boundary)
httpBody='\r\n'.join(data)

print type(httpBody)
print httpBody

postDataUrl='http://xxxxxxxx'
req=urllib2.Request(postDataUrl,data=httpBody)


经过测试,使用上述方法发送一段二进制文件的时候,服务器报错,数据有问题!

问题就出在 '\r\n'.join(data)的编码,data内部拥有二进制数据,通过这种编码,可能是把数据转换为utf-8格式,当然有问题。



搜索了很多资料,查到可以使用requests库提交multipart/form-data 格式的数据

一个multipart/form-data 的表单数据,在http里面抓包如下:

#Content-Disposition: form-data;name="app_id"



123456

#-----------------------------7df23df2a0870

#Content-Disposition: form-data;name="version"



2256

-----------------------------7df23df2a0870

Content-Disposition:form-data; name="platform"



ios

-----------------------------7df23df2a0870

Content-Disposition: form-data;name="libzip";filename="C:\Users\danwang3\Desktop\libmsc.zip"

Content-Type: application/x-zip-compressed



<二进制文件数据未显示>

---------------------------7df23df2a0870—



上述数据在requests里面可以模拟为:

files={'app_id':(None,'123456'),

'version':(None,'2256'),

'platform':(None,'ios'),

'libzip':('libmsc.zip',open('C:\Users\danwang3\Desktop\libmsc.zip','rb'),'application/x-zip-compressed')

}

发送上述post请求,也就是简单的

response=requests.post(url,files=files)

就这么简单

在官方网站上,requests模拟一个表单数据的格式如下:

files = {'name': (<filename>, <file object>,<content type>, <per-part headers>)}

这一行模拟出来的post数据为:



Content-Disposition: form-data; name=’name’;filename=<filename>
Content-Type: <content type>


<file object>
--boundary
如果filename 和 content-Type不写,那么响应模拟post的数据就不会有二者。



通常使用requests 不像使用urllib2那样可以自动管理cookie,不过如果获取到cookie

可以在requests请求里面一并将cookie发送出去

requests使用的cookie格式如下:

newCookie={}

newCookie['key1']='value1'

newCookie['key2]='value2'

newCookie['key3']='value3'

发送cookie可以使用:

response=requests.post(url,cookies=newCookie)

这样就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: