Python网络编程:HTTP请求与响应问题
在Python中,我们可以使用内置的库如requests
来实现HTTP请求与响应。以下是一些基本的问题和解决方法:
- 如何发送GET请求:
```python
import requests
response = requests.get(‘http://example.com‘)
print(response.text)
2. **如何发送POST请求**:
```python
data = {'key': 'value'}
response = requests.post('http://example.com/api', data=data)
print(response.json())
如何处理HTTP响应的状态码:
response = requests.get('http://example.com')
if response.status_code == 200:
print("Request successful!")
else:
print(f"Request failed with status code {response.status_code}.")
如何保存HTTP响应到本地文件:
response = requests.get('http://example.com')
with open('file.txt', 'wb') as f:
f.write(response.content)
以上就是关于Python中发送HTTP请求与处理响应的基本操作。
还没有评论,来说两句吧...