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

问题描述 投票:9回答:3

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

import urllib
import urllib2

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

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

python http get urllib2
3个回答
12
投票

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

import urllib
import urllib2

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

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


4
投票

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


2
投票

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

import urllib
import urllib2

params = urllib.urlencode(dict({'hello': 'there'}))
req = urllib2.urlopen('http://httpbin.org/get/?' + params)
req.read()
© www.soinside.com 2019 - 2024. All rights reserved.