urllib2.HTTPError: HTTP Error 401 while querying u

2019-04-09 22:27发布

So, I ve made corrections based on most of the answers under the same roof in stack overflow, I'm still unable to resolve this problem.

queryBingFor = "Google Fibre"
quoted_query = urllib.quote(queryBingFor)
account_key = "dslfkslkdfhsehwekhrwkj2187iwekjfkwej3"

rootURL = "https://api.datamarket.azure.com/Bing/Search/v1/"
searchURL = rootURL + "Image?format=json&Query=" + quoted_query
cred = base64.encodestring(accountKey)

reqBing = urllib2.Request(url=searchURL)
author = "Basic %s" % cred
reqBing.add_header('Authorization',author)

readURL = urllib2.urlopen(reqBing)

I know I'm missing out something in the above code, that gives me a:

urllib2.HTTPError: HTTP Error 401: The authorization type you provided is not supported.  Only Basic and OAuth are supported

Any clue on what the problem could be?

Thanks!

1条回答
2楼-- · 2019-04-09 23:00

So, here's the working code. The problem I was creating is the query keywords' format.

 queryBingFor = "'google fibre'" # the apostrophe's required as that is the format the API Url expects. 
 quoted_query = urllib.quote(queryBingFor)

 rootURL = "https://api.datamarket.azure.com/Bing/Search/"
 searchURL = rootURL + "Image?$format=json&Query=" + quoted_query

 password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
 password_mgr.add_password(None, searchURL,username,accountKey)

 handler = urllib2.HTTPBasicAuthHandler(password_mgr)
 opener = urllib2.build_opener(handler)
 urllib2.install_opener(opener)
 readURL = urllib2.urlopen(searchURL).read()

This should give the results in the respective JSON format. As I'm using urllib2's httpbasicauthhandler, the password's converted into base64 implicitly, I presume.

查看更多
登录 后发表回答