python的urllib库完成GET,POST请求

from urllib import parse,request
import json

# POST请求 当request中包含data参数的时候,是POST请求,反之是GET请求
textmod = {"username": "admin", "password": "admin", "rememberMe": True}
textmod = json.dumps(textmod).encode(encoding='utf-8')
header_dict = {'Accept': 'application/json', 'Content-Type': 'application/json'}
url = 'http://localhost:8080/api/authenticate'
req = request.Request(url=url, data=textmod, headers=header_dict)
res = request.urlopen(req)
res = res.read()# 默认获取到的是16进制'bytes'类型数据 Unicode编码
res = res.decode(encoding='utf-8') # 如果如需可读输出则需decode解码成对应编码




# GET GET请求没有data项,且请求url一般包含请求条件
textmod = {"query": "cluster.clusterNodeIp:"+ip}# key-query表示查询 value-表示查询条件
textmod = parse.urlencode(textmod) # 把查询条件转成url中的加密形式
print(textmod)# GET请求是添加在url中发出的,POST是夹在请求体内发出的
header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
               'Authorization': 'Bearer '+token}
# 前一部分为URL + '?' + 请求条件
url = 'http://localhost:8080/api/_search/analysis-tasks' + '?' + textmod
print(url)
req = request.Request(url=url, headers=header_dict) # GET无data项
res = request.urlopen(req)
res = str(res.read(), encoding='utf-8') # 将返回的bytes类型转为str类型
data = json.loads(res) # 如果是json/dict类型,这一步可以转为dict类型,前提是从str转

猜你喜欢

转载自blog.csdn.net/san_junipero/article/details/80448320