處理 content-type 錯誤
當你要求回應使用特定格式,但伺服器無法滿足時會發生什麼事?例如,你想要收到 XML 而不是 JSON。如果伺服器無法以 XML 回應,它會回傳一個特定的狀態碼,表示無法以要求的格式回覆。此情況會使用的狀態碼是 406 Not Acceptable,或簡寫為 406。伺服器的回應也常會包含一個 accept 標頭,列出它「可以」回應的所有格式。利用這點來了解該 API 可以回應哪些 content type。
本練習屬於課程
Python API 入門
練習說明
- 加上
accept標頭,向伺服器要求application/xml的 content-type 回應。 - 使用相關的狀態碼檢查伺服器是否不接受這個請求。
- 印出伺服器回應中可接受的 content 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)