簡體   English   中英

urllib.Request 刪除 Content-Type 標頭

[英]urllib.Request remove Content-Type header

我想從 POST 請求中刪除內容類型標頭。 我試過將標題設置為''

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標頭; 防止AbstractHTTPHandler使用默認的 Content-Type 標頭。

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

只是為了添加@falsetru的答案,

如果你需要過濾比這更多的標題, 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

如果你需要修改一個標題,而不是刪除它......它變得有點奇怪(至少這是我發現唯一有效的方法):

req.remove_header(header)
req.add_header(header, self.modify_headers[header.lower()])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM