处理 content-type 错误
当您请求以某种特定格式返回响应,而服务器无法满足该请求时会发生什么?例如,您希望接收 XML 而不是 JSON。如果服务器无法返回 XML,它会用一个特定的状态码来表示无法按请求的格式回复。本例中使用的状态码是 406 Not Acceptable,简称 406。服务器的响应中也常常包含一个 accept 头部,其中列出了它可以返回的所有响应格式。利用这一点来了解该 API 能返回哪些内容类型。
本练习是课程的一部分
Python 中的 API 入门
练习说明
- 添加一个
accept请求头,向服务器请求application/xmlcontent-type 的响应。 - 使用相应的状态码检查服务器是否未接受该请求。
- 打印服务器响应中可接受的内容类型列表。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Add a header to use in the request
headers = {____}
response = requests.get('http://localhost:3000/lyrics', headers=headers)
# Check if the server did not accept the request
if (response.____ == ____):
print('The server can not respond in XML')
# Print the accepted content types
print('These are the content types the server accepts: ' + response.____)
else:
print(response.text)