请输入手机号码
请输入密码
处理香港服务器API的错误响应,可以遵循以下步骤:
import requests
from requests.exceptions import HTTPError, ConnectionError
def call_api(url, params):
try:
response = requests.get(url, params=params)
response.raise_for_status() # 抛出HTTP错误
return response.json()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}') # 打印HTTP错误信息
# 根据状态码进行相应处理
if response.status_code == 400:
print('Bad Request: Please check your input.')
elif response.status_code == 401:
print('Unauthorized: Check your credentials.')
# ... 其他状态码处理
except ConnectionError as conn_err:
print(f'Connection error occurred: {conn_err}') # 打印连接错误信息
except Exception as err:
print(f'An unexpected error occurred: {err}') # 打印其他异常信息
return None
# 使用示例
result = call_api('https://api.example.com/data', {'key': 'value'})
if result:
print('API call successful:', result)
else:
print('API call failed.')通过以上步骤,可以有效地处理香港服务器API的错误响应,提升系统的健壮性和用户体验。