python发送HTTP请求的方法小结

yipeiwu_com5年前Python基础

本文实例讲述了python发送HTTP请求的方法。分享给大家供大家参考。具体如下:

这里包含 Python 使用 GET/HEAD/POST 方法进行 HTTP 请求

1. GET 方法:

>>> import httplib 
>>> conn = httplib.HTTPConnection("www.python.org") 
>>> conn.request("GET", "/index.html") 
>>> r1 = conn.getresponse() 
>>> print r1.status, r1.reason 
200 OK 
>>> data1 = r1.read() 
>>> conn.request("GET", "/parrot.spam") 
>>> r2 = conn.getresponse() 
>>> print r2.status, r2.reason 
404 Not Found 
>>> data2 = r2.read() 
>>> conn.close()

2. HEAD 方法:

>>> import httplib 
>>> conn = httplib.HTTPConnection("www.python.org") 
>>> conn.request("HEAD","/index.html") 
>>> res = conn.getresponse() 
>>> print res.status, res.reason 
200 OK 
>>> data = res.read() 
>>> print len(data) 
0
>>> data == '' 
True

3. POST 方法:

>>> import httplib, urllib 
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) 
>>> headers = {"Content-type": "application/x-www-form-urlencoded", 
...      "Accept": "text/plain"} 
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80") 
>>> conn.request("POST", "/cgi-bin/query", params, headers) 
>>> response = conn.getresponse() 
>>> print response.status, response.reason 
200 OK 
>>> data = response.read() 
>>> conn.close()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python Selenium Cookie 绕过验证码实现登录示例代码

Python Selenium Cookie 绕过验证码实现登录示例代码

之前介绍过通过cookie 绕过验证码实现登录的方法。这里并不多余,会增加分析和另外一种方法实现登录。 1、思路介绍  1.1、直接看代码,内有详细注释说明 # File...

python中字典dict常用操作方法实例总结

本文实例总结了python中字典dict常用操作方法。分享给大家供大家参考。具体如下: 下面的python代码展示python中字典的常用操作,字典在python开发中有着举足轻重的地位...

Python的Django框架中的select_related函数对QuerySet 查询的优化

Python的Django框架中的select_related函数对QuerySet 查询的优化

1. 实例的背景说明 假定一个个人信息系统,需要记录系统中各个人的故乡、居住地、以及到过的城市。数据库设计如下: Models.py 内容如下: from django.db i...

python模块hashlib(加密服务)知识点讲解

官方文案:https://docs.python.org/zh-cn/3/library/hashlib.html hashlib --- 安全哈希与消息摘要 Python的hashl...

python操作excel的方法(xlsxwriter包的使用)

本文介绍python操作excel的方法(xlsxwriter包的使用),具体内容如下 xlsxwriter包的安装 pip install xlsxwriter Workbook...