Python之request库请求header头中常见异常错误,如:空格、中文、float、int类型错误总结

 

常见场景错误类型简短log

 

1、空格
check_header_validity
    raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
requests.exceptions.InvalidHeader: Invalid return character or leading space in header: test

2、中文
    values[i] = one_value.encode('latin-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)

3、int
check_header_validity
    raise InvalidHeader("Value for header {%s: %s} must be of type str or "
requests.exceptions.InvalidHeader: Value for header {test: 12} must be of type str or bytes, not <class 'int'>

4、float
check_header_validity
    raise InvalidHeader("Value for header {%s: %s} must be of type str or "
requests.exceptions.InvalidHeader: Value for header {test: 1.2} must be of type str or bytes, not <class 'float'>

 

 

简易测试代码

# -*- coding: utf-8 -*-
# @Software: PyCharm
# @File : test.py 
# @Author : benjamin
# @Time : 2021/8/9 19:24

import requests

header = {
    "test":" "    # 分别输入:空格、中文、int、float不同类型字符串测试验证
}

data = {
    "test":" "
}

requests.get(url="http://127.0.0.1",headers=header,data=data)

 

 

常见异常完整版:

1、空格

D:\work_path\python\python.exe D:/code_path/python/test/test.py
Traceback (most recent call last):
  File "D:\code_path\python\test\test.py", line 17, in <module>
    requests.get(url="http://127.0.0.1",headers=header,data=data)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 452, in prepare_request
    p.prepare(
  File "D:\work_path\python\lib\site-packages\requests\models.py", line 314, in prepare
    self.prepare_headers(headers)
  File "D:\work_path\python\lib\site-packages\requests\models.py", line 448, in prepare_headers
    check_header_validity(header)
  File "D:\work_path\python\lib\site-packages\requests\utils.py", line 942, in check_header_validity
    raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
requests.exceptions.InvalidHeader: Invalid return character or leading space in header: test

 

2、中文

D:\work_path\python\python.exe D:/code_path/python/test/test.py
Traceback (most recent call last):
  File "D:\code_path\python\test\test.py", line 17, in <module>
    requests.get(url="http://127.0.0.1",headers=header,data=data)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "D:\work_path\python\lib\site-packages\urllib3\connectionpool.py", line 597, in urlopen
    httplib_response = self._make_request(conn, method, url,
  File "D:\work_path\python\lib\site-packages\urllib3\connectionpool.py", line 354, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "D:\work_path\python\lib\http\client.py", line 1256, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "D:\work_path\python\lib\http\client.py", line 1297, in _send_request
    self.putheader(hdr, value)
  File "D:\work_path\python\lib\http\client.py", line 1228, in putheader
    values[i] = one_value.encode('latin-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)

3、int

D:\work_path\python\python.exe D:/code_path/python/test/test.py
Traceback (most recent call last):
  File "D:\work_path\python\lib\site-packages\requests\utils.py", line 941, in check_header_validity
    if not pat.match(value):
TypeError: expected string or bytes-like object

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\code_path\python\test\test.py", line 17, in <module>
    requests.get(url="http://127.0.0.1",headers=header,data=data)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 452, in prepare_request
    p.prepare(
  File "D:\work_path\python\lib\site-packages\requests\models.py", line 314, in prepare
    self.prepare_headers(headers)
  File "D:\work_path\python\lib\site-packages\requests\models.py", line 448, in prepare_headers
    check_header_validity(header)
  File "D:\work_path\python\lib\site-packages\requests\utils.py", line 944, in check_header_validity
    raise InvalidHeader("Value for header {%s: %s} must be of type str or "
requests.exceptions.InvalidHeader: Value for header {test: 12} must be of type str or bytes, not <class 'int'>

 

4、float

D:\work_path\python\python.exe D:/code_path/python/test/test.py
Traceback (most recent call last):
  File "D:\work_path\python\lib\site-packages\requests\utils.py", line 941, in check_header_validity
    if not pat.match(value):
TypeError: expected string or bytes-like object

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\code_path\python\test\test.py", line 17, in <module>
    requests.get(url="http://127.0.0.1",headers=header,data=data)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "D:\work_path\python\lib\site-packages\requests\sessions.py", line 452, in prepare_request
    p.prepare(
  File "D:\work_path\python\lib\site-packages\requests\models.py", line 314, in prepare
    self.prepare_headers(headers)
  File "D:\work_path\python\lib\site-packages\requests\models.py", line 448, in prepare_headers
    check_header_validity(header)
  File "D:\work_path\python\lib\site-packages\requests\utils.py", line 944, in check_header_validity
    raise InvalidHeader("Value for header {%s: %s} must be of type str or "
requests.exceptions.InvalidHeader: Value for header {test: 1.2} must be of type str or bytes, not <class 'float'>

 

 

解决问题示例:

# -*- coding: utf-8 -*-
# @Software: PyCharm
# @File : test.py 
# @Time : 2021/8/9 19:24

import requests

def is_contain_chinese(check_str):
    """
    判断字符串中是否包含中文
    :param check_str: {str} 需要检测的字符串
    :return: {bool} 包含返回True, 不包含返回False
    """
    for ch in check_str:
        if u'\u4e00' <= ch <= u'\u9fff':
            return True
    return False

def setDictEncode(dict):
    """
    处理header中的特殊字符串 空格、int、float、中文
    :param dict:
    :return:
    """
    for key, value in dict.items():
        if value == " ":
            dict[key] = ""
        if type(value) == type(1):
            dict[key] = str(value)
            continue
        if type(value) == type(1.2):
            dict[key] = str(value)
            continue
        if is_contain_chinese(value):
            dict[key] = value.encode('UTF-8')
    return dict


header = {
    "test1": " ",
    "test2": 1,
    "test3": 1.2,
    "test4": "中文"
}

data = {
    "test":" "
}

requests.get(url="http://127.0.0.1",headers=setDictEncode(header),data=data)

 

PS:

    此处仅解决Python Request库报错的问题,不保证发送请求后接口返回正确,因为编码格式和数据类型已变更。

 

 

 

 

 

 

 

 

 

 

小兄弟,这里是提问区哦,在首页右上角=》创作=》写文章,即可发布自己的文章,祝你好运