登录  /  注册
Python中http请求方法库汇总
php中文网
发布: 2016-06-10 15:06:49
原创
710人浏览过

最近在使用python做接口测试,发现python中http请求方法有许多种,今天抽点时间把相关内容整理,分享给大家,具体内容如下所示:

一、python自带库----urllib2

python自带库urllib2使用的比较多,简单使用如下:

import urllib2
response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true')
print response.read() 
登录后复制

简单的get请求

import urllib2
import urllib
post_data = urllib.urlencode({})
response = urllib2.urlopen('http://localhost:8080/, post_data)
print response.read()
print response.getheaders() 
登录后复制

这就是最简单的urllib2发送post例子。代码比较多

二、python自带库--httplib

httplib是一个相对底层的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('http://localhost:8080).text 
登录后复制

就一句话,再来看看post请求

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text 
登录后复制

也很简单。

再看看如果要认证:

url = 'http://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
登录后复制

相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学