我想从 POST 请求中删除内容类型 header 。我尝试将 header 设置为 ''
try:
from urllib.request import Request, urlopen
except ImportError:
from urllib2 import Request, urlopen
url = 'https://httpbin.org/post'
test_data = 'test'
req = Request(url, test_data.encode(), headers={'Content-Type': ''})
req.get_method = lambda: 'POST'
print(urlopen(req).read().decode())
但这会发送:
{
// ...
"headers": {
"Content-Type": "", // ...
}
// ...
}
我希望它做的是根本不发送 Content-Type,而不是一个空白的。默认情况下,它是 application/x-www-form-urlencoded
。
这可以通过 requests
轻松实现:
print(requests.post(url, test_data).text)
但这是我需要分发的脚本,所以不能有依赖关系。我需要它完全没有 Content-Type,因为服务器非常挑剔,所以我不能使用 text/plain
或 application/octet-stream
。
最佳答案
您可以指定自定义处理程序:
try:
from urllib.request import Request, urlopen, build_opener, BaseHandler
except ImportError:
from urllib2 import Request, urlopen, build_opener, BaseHandler
url = 'https://httpbin.org/post'
test_data = 'test'
class ContentTypeRemover(BaseHandler):
def http_request(self, req):
if req.has_header('Content-type'):
req.remove_header('Content-type')
return req
https_request = http_request
opener = build_opener(ContentTypeRemover())
req = Request(url, test_data.encode())
print(opener.open(req).read().decode())
另一种(hacky)方式:对请求对象进行猴子修补以假装那里已经有 Content-type
header ;防止 AbstractHTTPHandler
成为默认的 Content-Type header 。
req = Request(url, test_data.encode())
req.has_header = lambda header_name: (header_name == 'Content-type' or
Request.has_header(req, header_name))
print(urlopen(req).read().decode())
关于python - urllib.Request 删除 Content-Type header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44352615/