import urllib.request
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36",
"Host": ""
}
debug = True
import traceback
def g_post2(url, data, domain):
try:
headers['Host'] = domain
opener = urllib.request.build_opener()
opener.addheaders = [
('User-Agent', headers['User-Agent']),
('Host', domain)
]
print(opener.addheaders)
return opener.open(url, data, timeout=2).read().decode()
except Exception as e:
print(e)
if debug:
traceback.print_exc()
print(g_post2('http://httpbin.org/post','data'.encode(), 'qq.com'))
输出的结果看设置的 UA 是生效了,但设置的 Host 没有生效。是不是设置的 Host 被后面的 open 覆盖掉了,但是 open 又没提供 headers 设置参数。
[('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'), ('Host', 'qq.com')]
{
"args": {},
"data": "",
"files": {},
"form": {
"data": ""
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "4",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-6146527f-471edcb1073f7ebe3e0672a3"
},
"json": null,
"origin": "123.203.104.151",
"url": "http://httpbin.org/post"
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.