问题
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:
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.
来源:https://stackoverflow.com/questions/11728256/urllib2-httperror-http-error-401-while-querying-using-the-new-bing-api-in-azu