我正在测试一些我发送一些POST请求的应用程序,想要在请求中缺少某些标头时测试应用程序的行为,以验证它是否生成了正确的错误代码。
为此,我的代码如下。
header = {'Content-type': 'application/json'}
data = "hello world"
request = urllib2.Request(url, data, header)
f = urllib2.urlopen(request)
response = f.read()
问题是urllib2在发送POST请求时添加了自己的标题,如Content-Length,Accept-Encoding,但是我不希望urllib2添加任何标题,而不是我在上面标题dict中指定的标题,是有办法做到这一点,我尝试设置我不想要的其他标头,但他们仍然使用那些空值作为请求的一部分,我不想要。
答案 0 :(得分:0)
标题采用字典类型,下面使用chrome用户代理示例。对于所有标准和一些非搁浅的头字段,请查看here。您还需要使用urllib而不是urllib2对数据进行编码。这在python文档here
中都有提及import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()