如何使用参数创建GET请求?

2024-05-13 00:37:46 发布

您现在位置:Python中文网/ 问答频道 /正文

默认情况下,似乎(对我来说)每个带参数的urlopen()都会发送POST请求。如何将呼叫设置为发送GET?

import urllib
import urllib2

params = urllib.urlencode(dict({'hello': 'there'}))
urllib2.urlopen('http://httpbin.org/get', params)

urllib2.HTTPError: HTTP Error 405: METHOD NOT ALLOWED


Tags: importhttphello参数get情况paramsurllib2
3条回答

如果要发出GET请求,则需要传递查询字符串。 你用问号'?'在你的url末尾的params之前。

import urllib
import urllib2

params = urllib.urlencode(dict({'hello': 'there'}))
req = urllib2.urlopen('http://httpbin.org/get/?' + params)
req.read()

您可以使用与post请求大致相同的方式:

import urllib
import urllib2

params = urllib.urlencode({'hello':'there', 'foo': 'bar'})
urllib2.urlopen('http://somesite.com/get?' + params)

第二个参数只应在发出POST请求时提供,例如在发送application/x-www-form-urlencoded内容类型时。

当提供数据参数时,HTTP请求将是POST而不是GET。 改为尝试urllib2.urlopen('http://httpbin.org/get?hello=there')

相关问题 更多 >