Python语言中http请求方法库汇总
小标 2018-11-06 来源 : 阅读 765 评论 0

摘要:本文主要向大家介绍了Python语言中http请求方法库汇总,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

本文主要向大家介绍了Python语言中http请求方法库汇总,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

最近在使用python做接口测试,发现python中http请求方法有许多种,今天抽点时间把相关内容整理,分享给大家,具体内容如下所示:一、python自带库----urllib2python自带库urllib2使用的比较多,简单使用如下:import urllib2response = urllib2.urlopen('//localhost:8080/jenkins/api/json?pretty=true')print response.read() 简单的get请求import urllib2import urllibpost_data = urllib.urlencode({})response = urllib2.urlopen('//localhost:8080/, post_data)print response.read()print response.getheaders() 这就是最简单的urllib2发送post例子。代码比较多二、python自带库--httplibhttplib是一个相对底层的http请求模块,urlib就是基于httplib封装的。简单使用如下:import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status, r1.reason
data1 = r1.read()
conn.request("GET", "/parrot.spam")
r2 = conn.getresponse()
data2 = r2.read()
conn.close()简单的get请求我们再来看post请求import httplib, urllib
params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
data = response.read()
print data
conn.close()是不是觉得太复杂了。每次写还得再翻文档,看看第三种吧三、第三方库--requests发请get请求超级简单:print requests.get('//localhost:8080).text就一句话,再来看看post请求payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("//httpbin.org/post", data=payload)
print r.text也很简单。再看看如果要认证:url = '//localhost:8080'
r = requests.post(url, data={}, auth=HTTPBasicAuth('admin', 'admin'))
print r.status_code
print r.headers
print r.reason是不是比urllib2更简单多了吧,且requests自带json解析。这点非常棒python中的http请求 import urllib
params = urllib.urlencode({key:value,key:value})
resultHtml = urllib.urlopen('[API or 网址]',params)
result = resultHtml.read()
print result

本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程