使用urllib2进行POST调用而不是GET

alf*_*kim 55 python urllib urllib2

在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
Run Code Online (Sandbox Code Playgroud)

我可以看到服务器日志,当我将数据参数发送到urlopen时,它说我正在进行GET调用.

该库引发了404错误(未找到),这对于GET调用是正确的,POST调用处理得很好(我也尝试使用HTML表单中的POST).

小智 45

分阶段执行,并修改对象,如下所示:

# 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
Run Code Online (Sandbox Code Playgroud)

这种方式可以让你扩展到制造PUT,DELETE,HEADOPTIONS请求过,只是通过替换法的价值,甚至包裹起来的功能.根据您要执行的操作,您可能还需要一个不同的HTTP处理程序,例如,用于多文件上载.

  • 读起来太可怕了; 只找到代码就太难了. (5认同)
  • 我认为看到冗长的方式很有用,可能不是大多数情况,但有时应该调整一些特殊情况. (2认同)

Gre*_*egg 44

以前可能已经回答过:Python URLLib/URLLib2 POST.

您的服务器可能执行302重定向http://myserver/post_servicehttp://myserver/post_service/.执行302重定向时,请求从POST更改为GET(请参阅问题1401).尝试url改为http://myserver/post_service/.


Mic*_*ent 11

请求模块可以减轻你的痛苦.

url = 'http://myserver/post_service'
data = dict(name='joe', age='10')

r = requests.post(url, data=data, allow_redirects=True)
print r.content
Run Code Online (Sandbox Code Playgroud)

  • OP问"使用urllib2" (39认同)
  • 你的一个词的一个非常有趣的选择 (3认同)
  • 确实,这对我的情况绝对没有用。 (2认同)

Rob*_*wie 10

阅读urllib Missing Manual.从那里拉出以下简单的POST请求示例.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()
Run Code Online (Sandbox Code Playgroud)

正如@Michael Kent所建议的那样考虑请求,这很棒.

编辑:这说,我不知道为什么将数据传递给urlopen()不会导致POST请求; 这应该.我怀疑你的服务器正在重定向或行为不端.


Cor*_*erg 5

如果您提供数据参数(就像您正在做的那样),它应该发送一个POST:

来自文档:"当提供数据参数时,HTTP请求将是POST而不是GET"

所以...添加一些调试输出,以查看客户端的内容.

您可以将代码修改为此,然后重试:

import urllib
import urllib2

url = 'http://myserver/post_service'
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
content = opener.open(url, data=data).read()
Run Code Online (Sandbox Code Playgroud)