Python中httplib库的基本用法指南
发布时间:2023-12-23 23:21:40
Python中的httplib库提供了一个简单的接口来与HTTP服务器进行通信。本指南将介绍httplib库的基本用法,并提供一些使用示例。
1. 引入httplib库:
import httplib
2. 创建连接:
conn = httplib.HTTPConnection("example.com")
3. 发送GET请求:
conn.request("GET", "/path/to/resource")
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print data
4. 发送POST请求:
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
body = "user=test&pass=test"
conn.request("POST", "/path/to/resource", body, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print data
5. 发送带有查询参数的GET请求:
import urllib
params = urllib.urlencode({"param1": "value1", "param2": "value2"})
conn.request("GET", "/path/to/resource?" + params)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print data
6. 发送带有自定义请求头的请求:
headers = {"Custom-Header": "value"}
conn.request("GET", "/path/to/resource", headers=headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print data
7. 设置超时时间:
import socket
conn = httplib.HTTPConnection("example.com", timeout=10)
以上是httplib库的基本用法。你可以根据你的需求进行适当的调整和修改。
需要注意的是,httplib库在Python 3中已被废弃,推荐使用更先进的库,如requests。如果你使用的是Python 3,建议使用requests代替httplib。
希望本指南对你理解和使用httplib库有所帮助!
