Python2/3 使用 http digest(信息摘要) 认证获取数据 (auth)

1、http的认证方式请看:https://www.cnblogs.com/xzwblog/p/6834663.html

 

2、http OAuth认证方式(python2)

import sys

import urllib2

import json

main_url='192.168.1.1:8080'

http_url='http://'

api_url='/wiki/res/?size=1000'

usernames='admin'

passwords='admin'

authhandler = urllib2.HTTPDigestAuthHandler()
#构造一个摘要认证的句柄

authhandler.add_password("RESTful Web Services", main_url, usernames, passwords)
#参数1:域, 参数2:ip和端口地址 ,参数3:用户名,参数3: 密码

opener = urllib2.build_opener(authhandler)
#将摘要认证的句柄加入http构造器

urllib2.install_opener(opener)
#启动http

pagehandle=urllib2.Request(http_url+main_url+api_url)
#发请求

pagehandle.add_header('Accept', 'application/json')
#请求头设置

result = urllib2.urlopen(pagehandle)
#返回结果

print json.loads(result.read()).values() #json转换

 

2、http OAuth认证方式(python3):py3 中语法和urllib2 有一些变化,写法如下:

import urllib
import json

main_url= '192.168.1.1:8080'

http_url = 'http://'

api_url = '/wiki/device?ip=10.88.44.6'

usernames = 'admin'

passwords = 'admin'

password_mgr = urllib.request.HTTPDigestAuthHandler()

password_mgr.add_password("RESTful Web Services", main_url, usernames, passwords)

handler = urllib.request.build_opener(password_mgr)

opener = urllib.request.install_opener(handler)

pagehandle=urllib.request.Request(http_url+main_url+api_url)

pagehandle.add_header('Accept', 'application/json')

result = urllib.request.urlopen(pagehandle)

data = json.loads(result.read())

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值