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
總結
以上是生活随笔為你收集整理的python的request请求401_Python模拟HTTPS请求返回HTTP 401 unauthorized错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 专科学数控还是计算机,盘点适合专科男生学
- 下一篇: python偏函数和高阶函数_【Pyth