python中http请求方法库汇总

最近在使用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文档,如下

urllib2:https://docs.python.org/2/library/urllib2.html

httplib:https://docs.python.org/2/library/httplib.html?highlight=httplib

requests:http://www.python-requests.org/en/latest/

转载:https://www.cnblogs.com/landhu/p/5104628.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值