python常见状态码报错
时间: 2025-02-13 10:14:38 浏览: 36
### Python 中常见 HTTP 状态码报错及其解决方案
#### 1. 400 Bad Request
当服务器无法理解客户端发送的请求时会返回此状态码。这可能是由于语法错误或其他原因造成的。
```python
import requests
url = "http://example.com/api"
params = {"key": "value"}
try:
response = requests.get(url, params=params)
if response.status_code == 400:
print("Bad request error occurred.")
except Exception as e:
print(f"An exception occurred: {e}")
```
对于此类问题,建议检查请求 URL 和参数是否正确[^3]。
#### 2. 401 Unauthorized
该状态表示未授权访问资源。通常是因为缺少有效的认证凭证。
```python
from requests.auth import HTTPBasicAuth
response = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('username', 'password'))
if response.status_code == 401:
print("Unauthorized access attempt failed.")
```
确保提供了正确的用户名和密码或者其他形式的身份验证信息。
#### 3. 403 Forbidden
即使有合法身份证明也可能收到这个代码,意味着没有权限执行特定操作。
```python
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.post('https://api.example.com/protected-resource', headers=headers)
if response.status_code == 403:
print("Access forbidden due to insufficient permissions.")
```
确认应用程序具有足够的权限来调用 API 或者尝试联系管理员获取更多权限。
#### 4. 404 Not Found
表明所请求的内容不存在于服务器上。
```python
response = requests.get('https://nonexistentwebsite.com')
if response.status_code == 404:
print("The requested resource could not be found on the server.")
```
仔细核对目标网址拼写准确性;如果是在开发环境中,则需确认服务端已部署好相应接口。
#### 5. 500 Internal Server Error
这是一个通用的服务端内部错误指示符,具体成因可能多种多样。
```python
try:
response = requests.get('https://brokenapi.com')
if response.status_code >= 500 and response.status_code < 600:
print("Server encountered an unexpected condition which prevented it from fulfilling the request.")
except requests.exceptions.RequestException as err:
print ("Error:",err)
```
遇到这种情况应该向网站开发者报告 bug 并等待修复版本发布。
阅读全文
相关推荐


















