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

时间:2012-10-11 00:14:36

标签: python http get urllib2

默认情况下,(对我而言)每个带参数的urlopen()似乎都会发送一个POST请求。如何设置调用以发送GET?

import urllib
import urllib2

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

urllib2.HTTPError:HTTP错误405:方法不允许

3 个答案:

答案 0 :(得分:11)

您可以使用,与发布请求的方式非常相似:

import urllib
import urllib2

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

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

答案 1 :(得分:4)

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

答案 2 :(得分:2)

如果您要发出GET请求,则需要传递查询字符串。 你这样做是通过设置问号'?'在params之前的网址末尾。

import urllib
import urllib2

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