Python设置Host代理

概述

我们在客户端沙箱环境测试接口的时候,一般都是通过Charles设置,

Host Name:testcapp.com
Address: 10.167.192.17

那如果我们要是在通过Python脚本进行接口请求,在沙箱环境下,设置Host时要如何做呢?看下面代码设置:

配置Host

上代码:

配置Host,沙箱环境:

1
2
3
4
5
dataUrl = "https://10.167.192.17/tst/positions/ful/dat"
req = urllib2.Request(dataUrl)
req.add_header('Host', 'testcapp.com')
req.add_header('version', versionName)
resp = urllib2.urlopen(req)

正式线上环境:

1
2
3
4
dataUrl = "https://testcapp.com/tst/positions/ful/dat"
req = urllib2.Request(dataUrl)
req.add_header('version', versionName)
resp = urllib2.urlopen(req)

注意:Host一定要是正式线上的域名,而不是Ip地址,下边设置是不对的,我们习惯了Charles写法,如果按下面设置,header中Host的key就错了,语法就不对:

1
2
3
4
5
6
dataUrl = "https://testcapp.com/tst/positions/ful/dat"
req = urllib2.Request(dataUrl)
req.add_header('testcapp.com', '10.167.192.17')
req.add_header('version', versionName)
resp = urllib2.urlopen(req)
req.add_header('testcapp.com', 'testcapp.com')