学堂 学堂 学堂公众号手机端

Python中http请求方法库方法有哪些,怎么使用

lewis 6年前 (2019-10-25) 阅读数 8 #技术
在实际应用中,我们有时候会遇到“Python中http请求方法库方法有哪些,怎么使用”这样的问题,我们该怎样来处理呢?下文给大家介绍了解决方法,希望这篇“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封装的。简单使用如下:

importhttplib
conn=httplib.HTTPConnection("www.python.org")
conn.request("GET","/index.html")
r1=conn.getresponse()
printr1.status,r1.reason
data1=r1.read()
conn.request("GET","/parrot.spam")
r2=conn.getresponse()
data2=r2.read()
conn.close()

简单的get请求

我们再来看post请求

importhttplib,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()
printdata
conn.close()


是不是觉得太复杂了。每次写还得再翻文档,看看第三种吧

三、第三方库--requests

发请get请求超级简单:

printrequests.get('http://localhost:8080).text

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

payload={'key1':'value1','key2':'value2'}
r=requests.post("http://httpbin.org/post",data=payload)
printr.text

也很简单。

再看看如果要认证:

url='http://localhost:8080'
r=requests.post(url,data={},auth=HTTPBasicAuth('admin','admin'))
printr.status_code
printr.headers
printr.reason

是不是比urllib2更简单多了吧,且requests自带json解析。这点非常棒

python中的http请求

importurllib
params=urllib.urlencode({key:value,key:value})
resultHtml=urllib.urlopen('[APIor网址]',params)
result=resultHtml.read()
printresult



以上就是关于“Python中http请求方法库方法有哪些,怎么使用”的介绍了,感谢各位的阅读,希望这篇文章能帮助大家解决问题。如果想要了解更多知识,欢迎关注博信,小编每天都会为大家更新不同的知识。
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门