下面就来详细讲解Python httplib模块使用实例的攻略。
什么是httplib模块?
httplib是Python自带的HTTP客户端库,提供了HTTP协议相关的请求和响应处理功能。
httplib模块的使用方法
发送GET请求
使用httplib发送GET请求可以通过以下步骤进行:
- 引入httplib模块
python
import httplib
- 创建HTTP连接
python
conn = httplib.HTTPConnection("www.example.com")
- 发送请求
python
conn.request("GET", "/path/to/resource")
- 获取响应
python
response = conn.getresponse()
data = response.read()
- 关闭连接
python
conn.close()
发送POST请求
使用httplib发送POST请求可以通过以下步骤进行:
- 引入httplib和urllib模块
python
import httplib
import urllib
- 创建HTTP连接
python
conn = httplib.HTTPConnection("www.example.com")
- 构造请求参数
python
params = urllib.urlencode({'param1': 'value1', 'param2': 'value2'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
- 发送请求
python
conn.request("POST", "/path/to/resource", params, headers)
- 获取响应
python
response = conn.getresponse()
data = response.read()
- 关闭连接
python
conn.close()
示例说明
示例一:获取网页内容
import httplib
conn = httplib.HTTPConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
data = response.read()
print data
conn.close()
运行结果:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Example Terminal</title>
<style type="text/css">
...
示例二:提交表单
import httplib
import urllib
conn = httplib.HTTPConnection("www.example.com")
params = urllib.urlencode({'param1': 'value1', 'param2': 'value2'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn.request("POST", "/submit/form", params, headers)
response = conn.getresponse()
data = response.read()
print data
conn.close()
运行结果:
Form submitted successfully
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python httplib模块使用实例 - Python技术站