Python中http请求方法库汇总

yipeiwu_com5年前Python基础

最近在使用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

相关文章

selenium 多窗口切换的实现(windows)

在web应用中,常常会遇见点击某个链接会弹出一个新的窗口,或者是相互关联的web应用 ,这样要去操作新窗口中的元素,这时就需要主机切换到新窗口进行操作。。WebDriver 提供了swi...

python读取浮点数和读取文本文件示例

从文本文件中读入浮点数据,是最常见的任务之一,python没有scanf这样的输入函数,但我们可以利用正规表达式从读入的字符串中提取出浮点数 复制代码 代码如下:import refp...

基于pandas将类别属性转化为数值属性的方法

基于pandas将类别属性转化为数值属性的方法

离散特征的编码分为两种情况: 1、离散特征的取值之间没有大小的意义,比如color:[red,blue],那么就使用one-hot编码 2、离散特征的取值有大小的意义,比如size:[...

在Python中使用SQLite的简单教程

SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。...

Python3.7安装keras和TensorFlow的教程图解

Python3.7安装keras和TensorFlow的教程图解

win10 Python3.7安装keras深度学习集成包 TensorFlow 和Ubuntu下安装keras 在win10下安装 安装时必须检查你的python是否为64位,32位不...