首页 > 解决方案 > 无法解码对 JSON 的 HTTP 响应(Python3)

问题描述

我正在运行一系列 API 测试,而这个测试给了我一个错误。据我所知response.read(),将 HTTP 响应转换为二进制,然后decode()将该二进制转换为字符串,但它是一个空字符串。当我将二进制字符串复制粘贴到 Python3 ( b'{"error": {"code": "INVALID_TOKEN", "description": ""}}') 并发出decode()命令时,它工作正常。我什至可以导入jsonloads()调用该字符串。

谁能建议为什么会这样?

import http.client
import json

# Fake info
api = http.client.HTTPConnection('192.168.0.1', 12345)

def logout_user (p_token):
    headers = {"Content-type": "application/json",
               "Accept": "text/plain",
               'Authorization': 'Bearer {}'.format(p_token)}
    try:
        api.request(method='PATCH',
                    url='/logout_user',
                    headers=headers)

        response = api.getresponse()
        status = response.status
        reason = response.reason
        if status == 200:
            data = None
        else:
            logging.debug (response)
            logging.debug (response.read ())
            logging.debug (response.read ().decode('ascii'))
            logging.debug (type(response.read ()))
            logging.debug (type(response.read ().decode()))
            data = json.loads(response.read ().decode('ascii'))  # The error is caused at this line and I think it's because I am passing an empty string to loads

    # If there is some API error, log it, and re-raise a general Exception
    except Exception as e:
        logging.error (e)

        raise exceptions.api.UnknownApiError ()

    return (status, reason, data, )

错误:

[2021-02-20 17:43:02,398] <http.client.HTTPResponse object at 0x7f6891b29430>
[2021-02-20 17:43:02,399] b'{"error": {"code": "INVALID_TOKEN", "description": ""}}'
[2021-02-20 17:43:02,399]
[2021-02-20 17:43:02,399] <class 'bytes'>
[2021-02-20 17:43:02,399] <class 'str'>
[2021-02-20 17:43:02,399] Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
  File "./test_api.py", line 168, in logout_user
    data = json.loads(response.read ().decode('ascii'))
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./test_api.py", line 4447, in <module>
    logout_user__fake_token ()
  File "./test_api.py", line 1093, in logout_user__fake_token
    status, reason, data = logout_user (token)
  File "./test_api.py", line 174, in logout_user
    raise exceptions.api.UnknownApiError ()
exceptions.api.UnknownApiError: Unable to make API call

标签: pythonjsonpython-3.xapihttp

解决方案


response对象是“类文件”对象。您试图读取响应两次,但在第二次调用时您得到一个空字符串。

您可能希望将代码更改为以下内容:

content = response.read()
logging.debug (response)
logging.debug (content)
logging.debug (content.decode('ascii'))
data = json.loads(content.decode('ascii'))

推荐阅读