python的request请求401_Python模拟HTTPS请求返回HTTP 401 unauthorized错误

Python模拟HTTPS请求返回HTTP 401 unauthorized错误

开始是使用的 httplib模块,代码如下:

header = {"Content-type": "application/json", "Accept": "*/*" }

params = { ‘source‘:‘en‘, ‘target‘:‘es‘, ‘text‘:match.group(1) }

data = urllib.urlencode(params)

surl = urlparse(‘https://gateway.watsonplatform.net/language-translation/api/v2/translate‘)

#surl = urlparse(‘https://www.baidu.com/‘)

resContent = ‘‘

try:

conn = httplib.HTTPSConnection(surl.netloc)

conn.request(‘GET‘, surl.path + ‘?‘ + data)

response = conn.getresponse()

resContent = data + "
" + getAllAttrs(response) #response.read() #

except:

info=sys.exc_info()

resContent = getAllAttrs(info[0]) + getAllAttrs(info[1])后来经过一番搜索发现,httplib根本不支持需要身份验证的这种请求;

改为以下代码成功:

params = { ‘source‘:‘en‘, ‘target‘:‘es‘, ‘text‘:match.group(1) }

surl = ‘https://gateway.watsonplatform.net/language-translation/api/v2/translate?‘ + urllib.urlencode(params)

resContent = ‘‘

try:

passman = urllib2.HTTPPasswordMgrWithDefaultRealm() #创建域验证对象

passman.add_password(None, surl, "c9819718-4660-441c-9df7-07398950ea44", "qUvrJPSdPgOx") #设置域地址,用户名及密码

auth_handler = urllib2.HTTPBasicAuthHandler(passman) #生成处理与远程主机的身份验证的处理程序

opener = urllib2.build_opener(auth_handler) #返回一个openerDirector实例

urllib2.install_opener(opener) #安装一个openerDirector实例作为默认的开启者。

response = urllib2.urlopen(surl) #打开URL链接,返回Response对象

resContent = response.read() #读取响应内容

except:

info=sys.exc_info()

resContent = getAllAttrs(info[0]) + getAllAttrs(info[1]) #获取异常的详细信息支持需要身份验证的请求的模块有以下几个:

httplib2,urllib2,requests,pycurl

但我安装的Python 2.7.10默认只带了 urllib2,所以就选择使用它了。

原文:http://blog.csdn.net/testcs_dn/article/details/50451762

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值