如何使用Python中的请求基于服务器发送的Content-Type捕获响应?

问题描述 投票:0回答:1

我是python的新手,正在学习如何发出HTTP请求并将响应存储在变量中。

下面是我尝试发出POST请求的类似代码段。

import requests
import simplejson as json

api_url = https://jsonplaceholder.typicode.com/tickets
raw_body = {"searchBy":"city","searchValue":"1","processed":9,"size":47,"filter":{"cityCode":["BA","KE","BE"],"tickets":["BLUE"]}}
raw_header = {"X-Ticket-id": "1234567", "X-Ticket-TimeStamp": "11:01:1212", "X-Ticket-MessageId": "123", 'Content-Type': 'application/json'}

result = requests.post(api_url, headers=json.loads(raw_header), data=raw_body)

#Response Header
response_header_contentType = result.headers['Content-Type'] #---> I am getting response_header_contentType as "text/html; charset=utf-8"

#Trying to get the result in json format
response = result.json() # --> I am getting error at this line. May be because the server is sending the content type as "text/html" and I am trying to capture the json response.

控制台错误:

  Traceback (most recent call last):
  File "C:\sam\python-project\v4\makeApiRequest.py", line 45, in make_API_request
    response = result.json()
  File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\simplejson\__init__.py", line 525, in loads
    return _default_decoder.decode(s)
  File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\simplejson\decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "C:\Users\userName\AppData\Local\Programs\Python\Python37\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

因此,如何根据服务器使用请求发送的内容类型将响应存储在变量中。

有人可以在这里帮我吗。我也尝试使用谷歌搜索,但没有找到任何有关如何根据内容类型捕获响应的有用文档。

python http post python-requests
1个回答
0
投票

正如您已经说过的那样,您的contentType是'text / html'而不是'application / json',这通常意味着不能将其解码为json。

如果您查看文档https://2.python-requests.org/en/master/user/quickstart/#response-content您会发现有多种解码主体的方法,如果您已经知道您拥有'text / html',则可以使用response.text对其进行解码。

因此,根据内容类型区分如何解码数据是有意义的:

if result.headers['Content-Type'] == 'application/json':
   data = result.json()
elif result.headers['Content-Type'] == 'text/html':
   data = result.text
else:
   data = result.raw 
© www.soinside.com 2019 - 2024. All rights reserved.