urllib.请求删除ContentType头

2024-04-25 13:53:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从POST请求中删除content-type头。我已尝试将标题设置为''

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())

但这意味着:

^{pr2}$

我想让它做的是不发送任何内容类型,而不是一个空白的。默认情况下,它是application/x-www-form-urlencoded。在

这可以通过requests轻松实现:

print(requests.post(url, test_data).text)

但这是我需要分发的脚本,所以不能有依赖关系。我需要它完全没有内容类型,因为服务器非常挑剔,所以我不能使用text/plain或{}。在


Tags: textfromtestimporturl类型内容data
2条回答

只是为了补充@false tru的答案

如果你需要过滤更多的标题,req.headers不是你想要的,它更像这样:

class ContentTypeRemover(BaseHandler):
    def __init__(self, headers_to_filter={'Content-type'}): # set or dict works
        self.headers_to_filter = headers_to_filter

    def http_request(self, req):
        for header, value in req.header_items():
            if header in self.headers_to_filter:
                req.remove_header(header)
        return req
    https_request = http_request

如果你需要修改一个标题,而不是删除它。。有点奇怪(至少这是我发现的唯一有效的方法):

^{pr2}$

可以指定自定义处理程序:

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())

另一种方法是:monkey修补request对象,假装已经存在Content-type头;防止{}成为默认的内容类型头。在

^{pr2}$

相关问题 更多 >

    热门问题