关于 urllib2 和 POST 调用有很多东西,但我遇到了一个问题。
我正在尝试对服务进行简单的 POST 调用:
url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
'age' : '10'})
content = urllib2.urlopen(url=url, data=data).read()
print content
我可以看到服务器日志,它说当我发送数据时我正在执行 GET 调用
urlopen 的参数。
该库引发 404 错误(未找到),这对于 GET 调用是正确的,POST 调用处理得很好(我也在尝试在 HTML 表单中使用 POST)。
分阶段进行,并修改对象,如下所示:
# make a string with the request type in it:
method = "POST"
# create a handler. you can specify different handlers here (file uploads etc)
# but we go for the default
handler = urllib2.HTTPHandler()
# create an openerdirector instance
opener = urllib2.build_opener(handler)
# build a request
data = urllib.urlencode(dictionary_of_POST_fields_or_None)
request = urllib2.Request(url, data=data)
# add any other information you want
request.add_header("Content-Type",'application/json')
# overload the get method function with a small anonymous function...
request.get_method = lambda: method
# try it; don't forget to catch the result
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e
# check. Substitute with appropriate HTTP code.
if connection.code == 200:
data = connection.read()
else:
# handle the error case. connection.read() will still contain data
# if any was returned, but it probably won't be of any use
这种方式可以让你扩展到制作PUT
, DELETE
, HEAD
and OPTIONS
也可以请求,只需替换方法的值,甚至将其包装在函数中即可。根据您想要执行的操作,您可能还需要不同的 HTTP 处理程序,例如用于多文件上传。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)