2013-12-10 58 views
2

我想發送我的應用程序/ zip數據到服務器沒有pycurl或其他庫。我是cURL的新手。首先,我用這個代碼成功發送文本/ XML數據urllib2發佈ZIP文件錯誤

import urllib2 
req = urllib2.Request("http://192.168.79.131/rest", headers = {"Content-type" : "text/xml" , "Accept" : "*/*"} , data = '<income><name>acme7</name></income>') 
f = urllib2.urlopen(req) 

但現在我想上傳我的ZIP文件到服務器。我想這樣的代碼:

import urllib2 
zipPath = "c:/somedir/ways.zip" 
zipData = open(zipPath, "rb") 
req = urllib2.Request("http://192.168.79.131/rest", headers = {"Content-type" : "application/zip" , "Accept" : "*/*"} , data = zipData) 
f = urllib2.urlopen(req) 

我得到了這些錯誤:

Traceback (most recent call last): 
    File "<pyshell#25>", line 1, in <module> 
    f = urllib2.urlopen(req) 
    File "C:\Python27\lib\urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "C:\Python27\lib\urllib2.py", line 386, in open 
    protocol = req.get_type() 
    File "C:\Python27\lib\urllib2.py", line 248, in get_type 
    **raise ValueError, "unknown url type: %s" % self.__original 
ValueError: unknown url type: /rest/income** 

回答

0

你有沒有考慮使用類似Requests?它可以處理大量的urllib2的東西,所以你不必:

import requests 

url = 'http://httpbin.org/post' 
files = {'file': open('c:/somedir/ways.zip', 'rb')} 
r = requests.post(url, files=files) 
print r 

打印:

>>> <Response [200]> 
+0

我只想用deafult的Python庫。沒有額外的安裝... – user3088938

+0

是因爲你不能在這裏運行?或者你不認爲安裝lib是值得的嗎? – brandonscript

+0

我喜歡urllib2,因爲也許用戶不想安裝其他庫(剛到新手) – user3088938