diff --git a/src/requests/compat.py b/src/requests/compat.py index 095de1b6ca..3725bbb62a 100644 --- a/src/requests/compat.py +++ b/src/requests/compat.py @@ -10,6 +10,18 @@ import importlib import sys +# ------- +# urllib3 +# ------- +from urllib3 import __version__ as urllib3_version + +# Detect which major version of urllib3 is being used. +try: + is_urllib3_2 = int(urllib3_version.split('.')[0]) == 2 +except (TypeError, AttributeError): + # If we can't discern a version, prefer old functionality. + is_urllib3_2 = False + # ------------------- # Character Detection # ------------------- diff --git a/src/requests/utils.py b/src/requests/utils.py index ae6c42f6cb..5cbd8d6e6e 100644 --- a/src/requests/utils.py +++ b/src/requests/utils.py @@ -41,6 +41,7 @@ ) from .compat import parse_http_list as _parse_list_header from .compat import ( + is_urllib3_2, proxy_bypass, proxy_bypass_environment, quote, @@ -136,7 +137,9 @@ def super_len(o): total_length = None current_position = 0 - if isinstance(o, str): + if is_urllib3_2 and isinstance(o, str): + # urllib3 2.x treats all strings as utf-8 instead + # of latin-1 (iso-8859-1) like http.client. o = o.encode("utf-8") if hasattr(o, "__len__"):