日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

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

發(fā)布時(shí)間:2025/3/15 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python的request请求401_Python模拟HTTPS请求返回HTTP 401 unauthorized错误 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python模擬HTTPS請(qǐng)求返回HTTP 401 unauthorized錯(cuò)誤

開始是使用的 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])后來經(jīng)過一番搜索發(fā)現(xiàn),httplib根本不支持需要身份驗(yàn)證的這種請(qǐng)求;

改為以下代碼成功:

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() #創(chuàng)建域驗(yàn)證對(duì)象

passman.add_password(None, surl, "c9819718-4660-441c-9df7-07398950ea44", "qUvrJPSdPgOx") #設(shè)置域地址,用戶名及密碼

auth_handler = urllib2.HTTPBasicAuthHandler(passman) #生成處理與遠(yuǎn)程主機(jī)的身份驗(yàn)證的處理程序

opener = urllib2.build_opener(auth_handler) #返回一個(gè)openerDirector實(shí)例

urllib2.install_opener(opener) #安裝一個(gè)openerDirector實(shí)例作為默認(rèn)的開啟者。

response = urllib2.urlopen(surl) #打開URL鏈接,返回Response對(duì)象

resContent = response.read() #讀取響應(yīng)內(nèi)容

except:

info=sys.exc_info()

resContent = getAllAttrs(info[0]) + getAllAttrs(info[1]) #獲取異常的詳細(xì)信息支持需要身份驗(yàn)證的請(qǐng)求的模塊有以下幾個(gè):

httplib2,urllib2,requests,pycurl

但我安裝的Python 2.7.10默認(rèn)只帶了?urllib2,所以就選擇使用它了。

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

總結(jié)

以上是生活随笔為你收集整理的python的request请求401_Python模拟HTTPS请求返回HTTP 401 unauthorized错误的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。