国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中http請求方法庫匯總

2019-11-25 16:59:37
字體:
來源:轉載
供稿:網(wǎng)友

最近在使用python做接口測試,發(fā)現(xiàn)python中http請求方法有許多種,今天抽點時間把相關內容整理,分享給大家,具體內容如下所示:

一、python自帶庫----urllib2

python自帶庫urllib2使用的比較多,簡單使用如下:

import urllib2response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true')print response.read() 

簡單的get請求

import urllib2import urllibpost_data = urllib.urlencode({})response = urllib2.urlopen('http://localhost:8080/, post_data)print response.read()print response.getheaders() 

這就是最簡單的urllib2發(fā)送post例子。代碼比較多

二、python自帶庫--httplib

httplib是一個相對底層的http請求模塊,urlib就是基于httplib封裝的。簡單使用如下:

import httplibconn = httplib.HTTPConnection("www.python.org")conn.request("GET", "/index.html")r1 = conn.getresponse()print r1.status, r1.reasondata1 = r1.read()conn.request("GET", "/parrot.spam")r2 = conn.getresponse()data2 = r2.read()conn.close() 

簡單的get請求

我們再來看post請求

import httplib, urllibparams = 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 dataconn.close() 

是不是覺得太復雜了。每次寫還得再翻文檔,看看第三種吧

三、第三方庫--requests

發(fā)請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_codeprint r.headersprint r.reason 

是不是比urllib2更簡單多了吧,且requests自帶json解析。這點非常棒

python中的http請求

import urllibparams = urllib.urlencode({key:value,key:value})resultHtml = urllib.urlopen('[API or 網(wǎng)址]',params)result = resultHtml.read()print result

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 清原| 临湘市| 河西区| 涟水县| 太仆寺旗| 福鼎市| 乐平市| 汕尾市| 秭归县| 睢宁县| 晋中市| 中方县| 岫岩| 高邑县| 通渭县| 民丰县| 德化县| 宿州市| 会东县| 邯郸县| 天镇县| 东台市| 肇东市| 精河县| 新余市| 施甸县| 闽清县| 沾化县| 会宁县| 酉阳| 墨竹工卡县| 泸西县| 志丹县| 来宾市| 贵南县| 潞西市| 获嘉县| 依兰县| 常德市| 庆城县| 桃江县|