<p dir="auto">While all other protocols are working, I can't access an URL using an HTTPS-proxy (<a href="https://stackoverflow.com/questions/71150284/python-request-https-proxy-errno-111-connection-refused" rel="nofollow">StackOverflow</a>)</p>
<h2 dir="auto">Expected Result</h2>
<p dir="auto">Open an HTTPS-URL using HTTPS-proxy.</p>

<h2 dir="auto">Actual Result</h2>
<p dir="auto">[Errno 111] Connection refused</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="---------------------------------------------------------------------------
ConnectionRefusedError                    Traceback (most recent call last)
[/usr/local/lib/python3.7/dist-packages/urllib3/connection.py](https://localhost:8080/#) in _new_conn(self)
    158             conn = connection.create_connection(
--&gt; 159                 (self._dns_host, self.port), self.timeout, **extra_kw)
    160 

14 frames
[/usr/local/lib/python3.7/dist-packages/urllib3/util/connection.py](https://localhost:8080/#) in create_connection(address, timeout, source_address, socket_options)
     79     if err is not None:
---&gt; 80         raise err
     81 

[/usr/local/lib/python3.7/dist-packages/urllib3/util/connection.py](https://localhost:8080/#) in create_connection(address, timeout, source_address, socket_options)
     69                 sock.bind(source_address)
---&gt; 70             sock.connect(sa)
     71             return sock

ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

NewConnectionError                        Traceback (most recent call last)
[/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py](https://localhost:8080/#) in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    593             if is_new_proxy_conn:
--&gt; 594                 self._prepare_proxy(conn)
    595 

[/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py](https://localhost:8080/#) in _prepare_proxy(self, conn)
    804         conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
--&gt; 805         conn.connect()
    806 

[/usr/local/lib/python3.7/dist-packages/urllib3/connection.py](https://localhost:8080/#) in connect(self)
    300         # Add certificate verification
--&gt; 301         conn = self._new_conn()
    302         hostname = self.host

[/usr/local/lib/python3.7/dist-packages/urllib3/connection.py](https://localhost:8080/#) in _new_conn(self)
    167             raise NewConnectionError(
--&gt; 168                 self, &quot;Failed to establish a new connection: %s&quot; % e)
    169 

NewConnectionError: &lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7fc4f55256d0&gt;: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last)
[/usr/local/lib/python3.7/dist-packages/requests/adapters.py](https://localhost:8080/#) in send(self, request, stream, timeout, verify, cert, proxies)
    449                     retries=self.max_retries,
--&gt; 450                     timeout=timeout
    451                 )

[/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py](https://localhost:8080/#) in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    637             retries = retries.increment(method, url, error=e, _pool=self,
--&gt; 638                                         _stacktrace=sys.exc_info()[2])
    639             retries.sleep()

[/usr/local/lib/python3.7/dist-packages/urllib3/util/retry.py](https://localhost:8080/#) in increment(self, method, url, response, error, _pool, _stacktrace)
    398         if new_retry.is_exhausted():
--&gt; 399             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    400 

MaxRetryError: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7fc4f55256d0&gt;: Failed to establish a new connection: [Errno 111] Connection refused')))

During handling of the above exception, another exception occurred:

ProxyError                                Traceback (most recent call last)
[&lt;ipython-input-5-0042a445fda6&gt;](https://localhost:8080/#) in &lt;module&gt;()
      5 print(proxy_url)
      6 
----&gt; 7 r = requests.get('https://google.com/', proxies = {protocol: proxy_url})
      8 r.status_code

[/usr/local/lib/python3.7/dist-packages/requests/api.py](https://localhost:8080/#) in get(url, params, **kwargs)
     73     &quot;&quot;&quot;
     74 
---&gt; 75     return request('get', url, params=params, **kwargs)
     76 
     77 

[/usr/local/lib/python3.7/dist-packages/requests/api.py](https://localhost:8080/#) in request(method, url, **kwargs)
     59     # cases, and look like a memory leak in others.
     60     with sessions.Session() as session:
---&gt; 61         return session.request(method=method, url=url, **kwargs)
     62 
     63 

[/usr/local/lib/python3.7/dist-packages/requests/sessions.py](https://localhost:8080/#) in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    527         }
    528         send_kwargs.update(settings)
--&gt; 529         resp = self.send(prep, **send_kwargs)
    530 
    531         return resp

[/usr/local/lib/python3.7/dist-packages/requests/sessions.py](https://localhost:8080/#) in send(self, request, **kwargs)
    643 
    644         # Send the request
--&gt; 645         r = adapter.send(request, **kwargs)
    646 
    647         # Total elapsed time of the request (approximately)

[/usr/local/lib/python3.7/dist-packages/requests/adapters.py](https://localhost:8080/#) in send(self, request, stream, timeout, verify, cert, proxies)
    511 
    512             if isinstance(e.reason, _ProxyError):
--&gt; 513                 raise ProxyError(e, request=request)
    514 
    515             if isinstance(e.reason, _SSLError):

ProxyError: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7fc4f55256d0&gt;: Failed to establish a new connection: [Errno 111] Connection refused')))"><pre class="notranslate"><code class="notranslate">---------------------------------------------------------------------------
ConnectionRefusedError                    Traceback (most recent call last)
[/usr/local/lib/python3.7/dist-packages/urllib3/connection.py](https://localhost:8080/#) in _new_conn(self)
    158             conn = connection.create_connection(
--&gt; 159                 (self._dns_host, self.port), self.timeout, **extra_kw)
    160 

14 frames
[/usr/local/lib/python3.7/dist-packages/urllib3/util/connection.py](https://localhost:8080/#) in create_connection(address, timeout, source_address, socket_options)
     79     if err is not None:
---&gt; 80         raise err
     81 

[/usr/local/lib/python3.7/dist-packages/urllib3/util/connection.py](https://localhost:8080/#) in create_connection(address, timeout, source_address, socket_options)
     69                 sock.bind(source_address)
---&gt; 70             sock.connect(sa)
     71             return sock

ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

NewConnectionError                        Traceback (most recent call last)
[/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py](https://localhost:8080/#) in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    593             if is_new_proxy_conn:
--&gt; 594                 self._prepare_proxy(conn)
    595 

[/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py](https://localhost:8080/#) in _prepare_proxy(self, conn)
    804         conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
--&gt; 805         conn.connect()
    806 

[/usr/local/lib/python3.7/dist-packages/urllib3/connection.py](https://localhost:8080/#) in connect(self)
    300         # Add certificate verification
--&gt; 301         conn = self._new_conn()
    302         hostname = self.host

[/usr/local/lib/python3.7/dist-packages/urllib3/connection.py](https://localhost:8080/#) in _new_conn(self)
    167             raise NewConnectionError(
--&gt; 168                 self, "Failed to establish a new connection: %s" % e)
    169 

NewConnectionError: &lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7fc4f55256d0&gt;: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last)
[/usr/local/lib/python3.7/dist-packages/requests/adapters.py](https://localhost:8080/#) in send(self, request, stream, timeout, verify, cert, proxies)
    449                     retries=self.max_retries,
--&gt; 450                     timeout=timeout
    451                 )

[/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py](https://localhost:8080/#) in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    637             retries = retries.increment(method, url, error=e, _pool=self,
--&gt; 638                                         _stacktrace=sys.exc_info()[2])
    639             retries.sleep()

[/usr/local/lib/python3.7/dist-packages/urllib3/util/retry.py](https://localhost:8080/#) in increment(self, method, url, response, error, _pool, _stacktrace)
    398         if new_retry.is_exhausted():
--&gt; 399             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    400 

MaxRetryError: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7fc4f55256d0&gt;: Failed to establish a new connection: [Errno 111] Connection refused')))

During handling of the above exception, another exception occurred:

ProxyError                                Traceback (most recent call last)
[&lt;ipython-input-5-0042a445fda6&gt;](https://localhost:8080/#) in &lt;module&gt;()
      5 print(proxy_url)
      6 
----&gt; 7 r = requests.get('https://google.com/', proxies = {protocol: proxy_url})
      8 r.status_code

[/usr/local/lib/python3.7/dist-packages/requests/api.py](https://localhost:8080/#) in get(url, params, **kwargs)
     73     """
     74 
---&gt; 75     return request('get', url, params=params, **kwargs)
     76 
     77 

[/usr/local/lib/python3.7/dist-packages/requests/api.py](https://localhost:8080/#) in request(method, url, **kwargs)
     59     # cases, and look like a memory leak in others.
     60     with sessions.Session() as session:
---&gt; 61         return session.request(method=method, url=url, **kwargs)
     62 
     63 

[/usr/local/lib/python3.7/dist-packages/requests/sessions.py](https://localhost:8080/#) in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    527         }
    528         send_kwargs.update(settings)
--&gt; 529         resp = self.send(prep, **send_kwargs)
    530 
    531         return resp

[/usr/local/lib/python3.7/dist-packages/requests/sessions.py](https://localhost:8080/#) in send(self, request, **kwargs)
    643 
    644         # Send the request
--&gt; 645         r = adapter.send(request, **kwargs)
    646 
    647         # Total elapsed time of the request (approximately)

[/usr/local/lib/python3.7/dist-packages/requests/adapters.py](https://localhost:8080/#) in send(self, request, stream, timeout, verify, cert, proxies)
    511 
    512             if isinstance(e.reason, _ProxyError):
--&gt; 513                 raise ProxyError(e, request=request)
    514 
    515             if isinstance(e.reason, _SSLError):

ProxyError: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7fc4f55256d0&gt;: Failed to establish a new connection: [Errno 111] Connection refused')))
</code></pre></div>

<h2 dir="auto">Reproduction Steps</h2>
<p dir="auto">Here is also a google <a href="https://colab.research.google.com/drive/1mlRyfHna4jH1R27SYJoRO9udoQYu5UsB?usp=sharing" rel="nofollow">colab</a> that reproduces this issue.</p>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="import requests
import random

PROXY_LIST_URL = 'https://proxylist.geonode.com/api/proxy-list?limit=50&amp;page=1&amp;sort_by=lastChecked&amp;sort_type=desc&amp;protocols=https'

proxies = requests.get(PROXY_LIST_URL).json()['data']

proxy = random.choice(proxies)

protocol = proxy['protocols'][0]
proxy_url = f&quot;{protocol}://{proxy['ip']}:{proxy['port']}&quot;
print(proxy_url)

r = requests.get('https://google.com', proxies = {protocol: proxy_url})
print(r.status_code)"><pre class="notranslate"><span class="pl-k">import</span> <span class="pl-s1">requests</span>
<span class="pl-k">import</span> <span class="pl-s1">random</span>

<span class="pl-v">PROXY_LIST_URL</span> <span class="pl-c1">=</span> <span class="pl-s">'https://proxylist.geonode.com/api/proxy-list?limit=50&amp;page=1&amp;sort_by=lastChecked&amp;sort_type=desc&amp;protocols=https'</span>

<span class="pl-s1">proxies</span> <span class="pl-c1">=</span> <span class="pl-s1">requests</span>.<span class="pl-en">get</span>(<span class="pl-v">PROXY_LIST_URL</span>).<span class="pl-en">json</span>()[<span class="pl-s">'data'</span>]

<span class="pl-s1">proxy</span> <span class="pl-c1">=</span> <span class="pl-s1">random</span>.<span class="pl-en">choice</span>(<span class="pl-s1">proxies</span>)

<span class="pl-s1">protocol</span> <span class="pl-c1">=</span> <span class="pl-s1">proxy</span>[<span class="pl-s">'protocols'</span>][<span class="pl-c1">0</span>]
<span class="pl-s1">proxy_url</span> <span class="pl-c1">=</span> <span class="pl-s">f"<span class="pl-s1"><span class="pl-kos">{</span><span class="pl-s1">protocol</span><span class="pl-kos">}</span></span>://<span class="pl-s1"><span class="pl-kos">{</span><span class="pl-s1">proxy</span>[<span class="pl-s">'ip'</span>]<span class="pl-kos">}</span></span>:<span class="pl-s1"><span class="pl-kos">{</span><span class="pl-s1">proxy</span>[<span class="pl-s">'port'</span>]<span class="pl-kos">}</span></span>"</span>
<span class="pl-en">print</span>(<span class="pl-s1">proxy_url</span>)

<span class="pl-s1">r</span> <span class="pl-c1">=</span> <span class="pl-s1">requests</span>.<span class="pl-en">get</span>(<span class="pl-s">'https://google.com'</span>, <span class="pl-s1">proxies</span> <span class="pl-c1">=</span> {<span class="pl-s1">protocol</span>: <span class="pl-s1">proxy_url</span>})
<span class="pl-en">print</span>(<span class="pl-s1">r</span>.<span class="pl-s1">status_code</span>)</pre></div>
<h2 dir="auto">System Information</h2>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="$ python -m requests.help"><pre class="notranslate"><code class="notranslate">$ python -m requests.help
</code></pre></div>
<div class="highlight highlight-source-json notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="{
  &quot;chardet&quot;: {
    &quot;version&quot;: &quot;3.0.4&quot;
  },
  &quot;charset_normalizer&quot;: {
    &quot;version&quot;: &quot;2.0.12&quot;
  },
  &quot;cryptography&quot;: {
    &quot;version&quot;: &quot;&quot;
  },
  &quot;idna&quot;: {
    &quot;version&quot;: &quot;2.10&quot;
  },
  &quot;implementation&quot;: {
    &quot;name&quot;: &quot;CPython&quot;,
    &quot;version&quot;: &quot;3.7.12&quot;
  },
  &quot;platform&quot;: {
    &quot;release&quot;: &quot;5.4.144+&quot;,
    &quot;system&quot;: &quot;Linux&quot;
  },
  &quot;pyOpenSSL&quot;: {
    &quot;openssl_version&quot;: &quot;&quot;,
    &quot;version&quot;: null
  },
  &quot;requests&quot;: {
    &quot;version&quot;: &quot;2.27.1&quot;
  },
  &quot;system_ssl&quot;: {
    &quot;version&quot;: &quot;1010100f&quot;
  },
  &quot;urllib3&quot;: {
    &quot;version&quot;: &quot;1.24.3&quot;
  },
  &quot;using_charset_normalizer&quot;: false,
  &quot;using_pyopenssl&quot;: false
}"><pre class="notranslate">{
  <span class="pl-ent">"chardet"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>3.0.4<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"charset_normalizer"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>2.0.12<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"cryptography"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span><span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"idna"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>2.10<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"implementation"</span>: {
    <span class="pl-ent">"name"</span>: <span class="pl-s"><span class="pl-pds">"</span>CPython<span class="pl-pds">"</span></span>,
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>3.7.12<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"platform"</span>: {
    <span class="pl-ent">"release"</span>: <span class="pl-s"><span class="pl-pds">"</span>5.4.144+<span class="pl-pds">"</span></span>,
    <span class="pl-ent">"system"</span>: <span class="pl-s"><span class="pl-pds">"</span>Linux<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"pyOpenSSL"</span>: {
    <span class="pl-ent">"openssl_version"</span>: <span class="pl-s"><span class="pl-pds">"</span><span class="pl-pds">"</span></span>,
    <span class="pl-ent">"version"</span>: <span class="pl-c1">null</span>
  },
  <span class="pl-ent">"requests"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>2.27.1<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"system_ssl"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>1010100f<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"urllib3"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>1.24.3<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"using_charset_normalizer"</span>: <span class="pl-c1">false</span>,
  <span class="pl-ent">"using_pyopenssl"</span>: <span class="pl-c1">false</span>
}</pre></div>
<p dir="auto"><a class="issue-link js-issue-link" data-error-text="Failed to load title" data-id="1446150654" data-permission-text="Title is private" data-url="https://github.com/foyoux/aligo/issues/55" data-hovercard-type="issue" data-hovercard-url="/foyoux/aligo/issues/55/hovercard" href="https://github.com/foyoux/aligo/issues/55">foyoux/aligo#55</a></p>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="from dataclasses import dataclass

import requests


@dataclass
class ShareToken(str):
    &quot;&quot;&quot;
    &gt;&gt;&gt; assert isinstance(ShareToken('xxx'), str)
    &quot;&quot;&quot;
    share_token: str = None
    expire_time: str = None
    expires_in: int = None

    def __new__(cls, *args, **kwargs):
        share_token = kwargs.get('share_token')
        if share_token is None:
            share_token = args[0]
        return super().__new__(cls, share_token)

    def __str__(self):
        return self.share_token


def main():
    share_token = ShareToken('xxx')
    resp = requests.get('https://github.com/', headers={
        # Why am I doing this?
        # Because the share_token has a short validity period,
        # but the program may need it for a long time,
        # the object used is convenient for updating in place when it fails.
        # Maybe I didn't express clearly,
        # but as far as my own application scenario is concerned,
        # this is the best way. Of course, these are not the point,
        # the point is that I think headers should allow subclasses of str or bytes. thanks
        'x-share-token': share_token
    })
    print(resp.status_code)


if __name__ == '__main__':
    main()"><pre class="notranslate"><span class="pl-k">from</span> <span class="pl-s1">dataclasses</span> <span class="pl-k">import</span> <span class="pl-s1">dataclass</span>

<span class="pl-k">import</span> <span class="pl-s1">requests</span>


<span class="pl-en">@<span class="pl-s1">dataclass</span></span>
<span class="pl-k">class</span> <span class="pl-v">ShareToken</span>(<span class="pl-s1">str</span>):
    <span class="pl-s">"""</span>
<span class="pl-s">    &gt;&gt;&gt; assert isinstance(ShareToken('xxx'), str)</span>
<span class="pl-s">    """</span>
    <span class="pl-s1">share_token</span>: <span class="pl-s1">str</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>
    <span class="pl-s1">expire_time</span>: <span class="pl-s1">str</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>
    <span class="pl-s1">expires_in</span>: <span class="pl-s1">int</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>

    <span class="pl-k">def</span> <span class="pl-en">__new__</span>(<span class="pl-s1">cls</span>, <span class="pl-c1">*</span><span class="pl-s1">args</span>, <span class="pl-c1">**</span><span class="pl-s1">kwargs</span>):
        <span class="pl-s1">share_token</span> <span class="pl-c1">=</span> <span class="pl-s1">kwargs</span>.<span class="pl-en">get</span>(<span class="pl-s">'share_token'</span>)
        <span class="pl-k">if</span> <span class="pl-s1">share_token</span> <span class="pl-c1">is</span> <span class="pl-c1">None</span>:
            <span class="pl-s1">share_token</span> <span class="pl-c1">=</span> <span class="pl-s1">args</span>[<span class="pl-c1">0</span>]
        <span class="pl-k">return</span> <span class="pl-en">super</span>().<span class="pl-en">__new__</span>(<span class="pl-s1">cls</span>, <span class="pl-s1">share_token</span>)

    <span class="pl-k">def</span> <span class="pl-en">__str__</span>(<span class="pl-s1">self</span>):
        <span class="pl-k">return</span> <span class="pl-s1">self</span>.<span class="pl-s1">share_token</span>


<span class="pl-k">def</span> <span class="pl-en">main</span>():
    <span class="pl-s1">share_token</span> <span class="pl-c1">=</span> <span class="pl-v">ShareToken</span>(<span class="pl-s">'xxx'</span>)
    <span class="pl-s1">resp</span> <span class="pl-c1">=</span> <span class="pl-s1">requests</span>.<span class="pl-en">get</span>(<span class="pl-s">'https://github.com/'</span>, <span class="pl-s1">headers</span><span class="pl-c1">=</span>{
        <span class="pl-c"># Why am I doing this?</span>
        <span class="pl-c"># Because the share_token has a short validity period,</span>
        <span class="pl-c"># but the program may need it for a long time,</span>
        <span class="pl-c"># the object used is convenient for updating in place when it fails.</span>
        <span class="pl-c"># Maybe I didn't express clearly,</span>
        <span class="pl-c"># but as far as my own application scenario is concerned,</span>
        <span class="pl-c"># this is the best way. Of course, these are not the point,</span>
        <span class="pl-c"># the point is that I think headers should allow subclasses of str or bytes. thanks</span>
        <span class="pl-s">'x-share-token'</span>: <span class="pl-s1">share_token</span>
    })
    <span class="pl-en">print</span>(<span class="pl-s1">resp</span>.<span class="pl-s1">status_code</span>)


<span class="pl-k">if</span> <span class="pl-s1">__name__</span> <span class="pl-c1">==</span> <span class="pl-s">'__main__'</span>:
    <span class="pl-en">main</span>()</pre></div>
<h2 dir="auto">Expected Result</h2>

<p dir="auto">The operation is successful, no error is reported, and 200 is printed out.</p>
<h2 dir="auto">Actual Result</h2>

<p dir="auto">It is OK under requests==2.27.1, but the latest 2.28.0 &amp; 2.28.1 reports an error "requests.exceptions.InvalidHeader: Header part (...."</p>
<div class="highlight highlight-source-shell notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="Traceback (most recent call last):
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/main.py&quot;, line 42, in &lt;module&gt;
    main()
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/main.py&quot;, line 27, in main
    resp = requests.get('https://github.com/', headers={
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/api.py&quot;, line 73, in get
    return request(&quot;get&quot;, url, params=params, **kwargs)
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/api.py&quot;, line 59, in request
    return session.request(method=method, url=url, **kwargs)
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/sessions.py&quot;, line 573, in request
    prep = self.prepare_request(req)
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/sessions.py&quot;, line 484, in prepare_request
    p.prepare(
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/models.py&quot;, line 369, in prepare
    self.prepare_headers(headers)
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/models.py&quot;, line 491, in prepare_headers
    check_header_validity(header)
  File &quot;/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/utils.py&quot;, line 1037, in check_header_validity
    raise InvalidHeader(
requests.exceptions.InvalidHeader: Header part (ShareToken(share_token='xxx', expire_time=None, expires_in=None)) from {'x-share-token': ShareToken(share_token='xxx', expire_time=None, expires_in=None)} must be of type str or bytes, not &lt;class '__main__.ShareToken'&gt;"><pre class="notranslate">Traceback (most recent call last):
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/main.py<span class="pl-pds">"</span></span>, line 42, <span class="pl-k">in</span> <span class="pl-k">&lt;</span>module<span class="pl-k">&gt;</span>
    <span class="pl-en">main</span>()
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/main.py<span class="pl-pds">"</span></span>, line 27, <span class="pl-k">in</span> main
    resp = requests.get(<span class="pl-s"><span class="pl-pds">'</span>https://github.com/<span class="pl-pds">'</span></span>, headers={
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/api.py<span class="pl-pds">"</span></span>, line 73, <span class="pl-k">in</span> get
    <span class="pl-k">return</span> request(<span class="pl-s"><span class="pl-pds">"</span>get<span class="pl-pds">"</span></span>, url, params=params, <span class="pl-k">**</span>kwargs)
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/api.py<span class="pl-pds">"</span></span>, line 59, <span class="pl-k">in</span> request
    <span class="pl-k">return</span> session.request(method=method, url=url, <span class="pl-k">**</span>kwargs)
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/sessions.py<span class="pl-pds">"</span></span>, line 573, <span class="pl-k">in</span> request
    prep = self.prepare_request(req)
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/sessions.py<span class="pl-pds">"</span></span>, line 484, <span class="pl-k">in</span> prepare_request
    p.prepare(
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/models.py<span class="pl-pds">"</span></span>, line 369, <span class="pl-k">in</span> prepare
    self.prepare_headers(headers)
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/models.py<span class="pl-pds">"</span></span>, line 491, <span class="pl-k">in</span> prepare_headers
    check_header_validity(header)
  File <span class="pl-s"><span class="pl-pds">"</span>/home/foyou/Desktop/projects/foyoux/aligo/venv/lib/python3.10/site-packages/requests/utils.py<span class="pl-pds">"</span></span>, line 1037, <span class="pl-k">in</span> check_header_validity
    raise InvalidHeader(
requests.exceptions.InvalidHeader: Header part (ShareToken(share_token=<span class="pl-s"><span class="pl-pds">'</span>xxx<span class="pl-pds">'</span></span>, expire_time=None, expires_in=None)) from {<span class="pl-s"><span class="pl-pds">'</span>x-share-token<span class="pl-pds">'</span></span>: ShareToken(share_token=<span class="pl-s"><span class="pl-pds">'</span>xxx<span class="pl-pds">'</span></span>, expire_time=None, expires_in=None)} must be of <span class="pl-c1">type</span> str or bytes, not <span class="pl-k">&lt;</span>class <span class="pl-s"><span class="pl-pds">'</span>__main__.ShareToken<span class="pl-pds">'</span></span><span class="pl-k">&gt;</span></pre></div>
<h2 dir="auto">Reproduction Steps</h2>
<p dir="auto">run this code</p>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="
from dataclasses import dataclass

import requests


@dataclass
class ShareToken(str):
    &quot;&quot;&quot;
    &gt;&gt;&gt; assert isinstance(ShareToken('xxx'), str)
    &quot;&quot;&quot;
    share_token: str = None
    expire_time: str = None
    expires_in: int = None

    def __new__(cls, *args, **kwargs):
        share_token = kwargs.get('share_token')
        if share_token is None:
            share_token = args[0]
        return super().__new__(cls, share_token)

    def __str__(self):
        return self.share_token


def main():
    share_token = ShareToken('xxx')
    resp = requests.get('https://github.com/', headers={
        # Why am I doing this?
        # Because the share_token has a short validity period,
        # but the program may need it for a long time,
        # the object used is convenient for updating in place when it fails.
        # Maybe I didn't express clearly,
        # but as far as my own application scenario is concerned,
        # this is the best way. Of course, these are not the point,
        # the point is that I think headers should allow subclasses of str or bytes. thanks
        'x-share-token': share_token
    })
    print(resp.status_code)


if __name__ == '__main__':
    main()"><pre class="notranslate"><span class="pl-k">from</span> <span class="pl-s1">dataclasses</span> <span class="pl-k">import</span> <span class="pl-s1">dataclass</span>

<span class="pl-k">import</span> <span class="pl-s1">requests</span>


<span class="pl-en">@<span class="pl-s1">dataclass</span></span>
<span class="pl-k">class</span> <span class="pl-v">ShareToken</span>(<span class="pl-s1">str</span>):
    <span class="pl-s">"""</span>
<span class="pl-s">    &gt;&gt;&gt; assert isinstance(ShareToken('xxx'), str)</span>
<span class="pl-s">    """</span>
    <span class="pl-s1">share_token</span>: <span class="pl-s1">str</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>
    <span class="pl-s1">expire_time</span>: <span class="pl-s1">str</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>
    <span class="pl-s1">expires_in</span>: <span class="pl-s1">int</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>

    <span class="pl-k">def</span> <span class="pl-en">__new__</span>(<span class="pl-s1">cls</span>, <span class="pl-c1">*</span><span class="pl-s1">args</span>, <span class="pl-c1">**</span><span class="pl-s1">kwargs</span>):
        <span class="pl-s1">share_token</span> <span class="pl-c1">=</span> <span class="pl-s1">kwargs</span>.<span class="pl-en">get</span>(<span class="pl-s">'share_token'</span>)
        <span class="pl-k">if</span> <span class="pl-s1">share_token</span> <span class="pl-c1">is</span> <span class="pl-c1">None</span>:
            <span class="pl-s1">share_token</span> <span class="pl-c1">=</span> <span class="pl-s1">args</span>[<span class="pl-c1">0</span>]
        <span class="pl-k">return</span> <span class="pl-en">super</span>().<span class="pl-en">__new__</span>(<span class="pl-s1">cls</span>, <span class="pl-s1">share_token</span>)

    <span class="pl-k">def</span> <span class="pl-en">__str__</span>(<span class="pl-s1">self</span>):
        <span class="pl-k">return</span> <span class="pl-s1">self</span>.<span class="pl-s1">share_token</span>


<span class="pl-k">def</span> <span class="pl-en">main</span>():
    <span class="pl-s1">share_token</span> <span class="pl-c1">=</span> <span class="pl-v">ShareToken</span>(<span class="pl-s">'xxx'</span>)
    <span class="pl-s1">resp</span> <span class="pl-c1">=</span> <span class="pl-s1">requests</span>.<span class="pl-en">get</span>(<span class="pl-s">'https://github.com/'</span>, <span class="pl-s1">headers</span><span class="pl-c1">=</span>{
        <span class="pl-c"># Why am I doing this?</span>
        <span class="pl-c"># Because the share_token has a short validity period,</span>
        <span class="pl-c"># but the program may need it for a long time,</span>
        <span class="pl-c"># the object used is convenient for updating in place when it fails.</span>
        <span class="pl-c"># Maybe I didn't express clearly,</span>
        <span class="pl-c"># but as far as my own application scenario is concerned,</span>
        <span class="pl-c"># this is the best way. Of course, these are not the point,</span>
        <span class="pl-c"># the point is that I think headers should allow subclasses of str or bytes. thanks</span>
        <span class="pl-s">'x-share-token'</span>: <span class="pl-s1">share_token</span>
    })
    <span class="pl-en">print</span>(<span class="pl-s1">resp</span>.<span class="pl-s1">status_code</span>)


<span class="pl-k">if</span> <span class="pl-s1">__name__</span> <span class="pl-c1">==</span> <span class="pl-s">'__main__'</span>:
    <span class="pl-en">main</span>()</pre></div>
<h2 dir="auto">System Information</h2>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="$ python -m requests.help"><pre class="notranslate"><code class="notranslate">$ python -m requests.help
</code></pre></div>
<div class="highlight highlight-source-json notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="{
  &quot;chardet&quot;: {
    &quot;version&quot;: null
  },
  &quot;charset_normalizer&quot;: {
    &quot;version&quot;: &quot;2.0.12&quot;
  },
  &quot;cryptography&quot;: {
    &quot;version&quot;: &quot;&quot;
  },
  &quot;idna&quot;: {
    &quot;version&quot;: &quot;3.3&quot;
  },
  &quot;implementation&quot;: {
    &quot;name&quot;: &quot;CPython&quot;,
    &quot;version&quot;: &quot;3.10.5&quot;
  },
  &quot;platform&quot;: {
    &quot;release&quot;: &quot;5.14.0-1051-oem&quot;,
    &quot;system&quot;: &quot;Linux&quot;
  },
  &quot;pyOpenSSL&quot;: {
    &quot;openssl_version&quot;: &quot;&quot;,
    &quot;version&quot;: null
  },
  &quot;requests&quot;: {
    &quot;version&quot;: &quot;2.28.1&quot;
  },
  &quot;system_ssl&quot;: {
    &quot;version&quot;: &quot;1010106f&quot;
  },
  &quot;urllib3&quot;: {
    &quot;version&quot;: &quot;1.26.12&quot;
  },
  &quot;using_charset_normalizer&quot;: true,
  &quot;using_pyopenssl&quot;: false
}"><pre class="notranslate">{
  <span class="pl-ent">"chardet"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-c1">null</span>
  },
  <span class="pl-ent">"charset_normalizer"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>2.0.12<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"cryptography"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span><span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"idna"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>3.3<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"implementation"</span>: {
    <span class="pl-ent">"name"</span>: <span class="pl-s"><span class="pl-pds">"</span>CPython<span class="pl-pds">"</span></span>,
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>3.10.5<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"platform"</span>: {
    <span class="pl-ent">"release"</span>: <span class="pl-s"><span class="pl-pds">"</span>5.14.0-1051-oem<span class="pl-pds">"</span></span>,
    <span class="pl-ent">"system"</span>: <span class="pl-s"><span class="pl-pds">"</span>Linux<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"pyOpenSSL"</span>: {
    <span class="pl-ent">"openssl_version"</span>: <span class="pl-s"><span class="pl-pds">"</span><span class="pl-pds">"</span></span>,
    <span class="pl-ent">"version"</span>: <span class="pl-c1">null</span>
  },
  <span class="pl-ent">"requests"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>2.28.1<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"system_ssl"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>1010106f<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"urllib3"</span>: {
    <span class="pl-ent">"version"</span>: <span class="pl-s"><span class="pl-pds">"</span>1.26.12<span class="pl-pds">"</span></span>
  },
  <span class="pl-ent">"using_charset_normalizer"</span>: <span class="pl-c1">true</span>,
  <span class="pl-ent">"using_pyopenssl"</span>: <span class="pl-c1">false</span>
}</pre></div>