使用python的requests 傳送multipart/form-data 請求
網上關於使用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)
這樣就可以了