urllib2发布ZIP文件错误

时间:2013-12-10 23:22:07

标签: python curl urllib2

我想将我的应用程序/ zip数据发送到没有pycurl或其他库的服务器。我是cURL的新手。首先,我使用此代码

成功发送了text / xml数据
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**

1 个答案:

答案 0 :(得分: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]>