Python网络编程:HTTP请求和响应问题示例
在Python中,我们可以使用内置的http.client
模块来发送HTTP请求和接收响应。下面是一个简单的示例:
发送GET请求:
import http.client
# 连接URL
conn = http.client.HTTPConnection('www.example.com')
# 发送GET请求
req = '/path/to/resource'
conn.request('GET', req)
# 获取响应
response = conn.getresponse()
# 打印响应状态码和内容
print("Status code:", response.status)
print("Response content:", response.read().decode())
发送POST请求:
import http.client
# 连接URL
conn = http.client.HTTPConnection('www.example.com')
# 发送POST请求
data = {'key1': 'value1', 'key2': 'value2'}
req = '/path/to/resource'
conn.request('POST', req, headers={'Content-Type': 'application/json'}}, data)
# 获取响应
response = conn.getresponse()
# 打印响应状态码和内容
print("Status code:", response.status)
print("Response content:", response.read().decode())
以上示例展示了如何使用Python的http.client
模块发送GET和POST请求,并接收响应。
还没有评论,来说两句吧...