python - urllib.Request 删除 Content-Type header

标签 python python-3.x http post

我想从 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/plainapplication/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/

相关文章:

python 理解和集合。接收错误

python - six.moves.builtins.range 在 Python 2 和 Python 3 中不一致

Java小程序使用httprespon

python - Struct.Error,必须是字节对象吗?

c# - Python脚本可以在Windows应用商店应用程序中执行吗?

python - 理解的符号表中的这些额外符号是什么?

python - Python 文档中 "mixin methods"的含义

python - Python 包的多个位置

java - Servlet 回复 getHttpConnection

http - 使用golang http包获取post数据