[英]HTTP Error 401: Unauthorized using urllib.request.urlopen
我在python中使用urllib.request嘗試從Teamcity下載一些構建信息。 該請求曾經在沒有用戶名和密碼的情況下工作,但是最近的安全更改意味着我必須使用用戶名和密碼。 因此,我更改了以下兩種解決方案的嘗試:
嘗試1)
url = 'http://<domain>/httpAuth/app/rest/buildTypes/<buildlabel>/builds/running:false?count=1&start=0'
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
top_level_url = "http://<domain>/httpAuth/app/rest/buildTypes/id:<buildlabel>/builds/running:false?count=1&start=0"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)
# use the opener to fetch a URL
opener.open(url)
嘗試2
url = 'http://<username>:<password>@<domain>/httpAuth/app/rest/buildTypes/id:buildlabel/builds/running:false?count=1&start=0'
rest_api = urllib.request.urlopen(url)
這兩個都返回“ HTTP錯誤401:未經授權”。 但是,如果我要打印'url'並將此輸出復制到瀏覽器中,則該鏈接可以正常工作。 但是當通過python使用時,出現上述錯誤。
我在另一個Perl腳本中使用了非常相似的東西,這也很完美。
*解決以下*
解決了這個使用。
credentials(url, username, password)
rest_api = urllib2.urlopen(url)
latest_build_info = rest_api.read()
latest_build_info = latest_build_info.decode("UTF-8")
# Then parse this xml for the information I want.
def credentials(self, url, username, password):
p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
作為旁注,然后我要下載文件。
credentials(url, username, password)
urllib2.urlretrieve(url, downloaded_file)
網址在哪里:
http://<teamcityServer>/repository/download/<build Label>/<BuildID>:id/Filename.zip
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.