I faced a trouble to properly encode a query string to use Bing image search API.
I got my account key for using Bing API, which contains "/" and "+". So when I try Bing example query like
http://api.bing.net/json.aspx?AppId=MY_APP_ID&Query=xbox site:microsoft.com&Sources=Image
I got reply that my AppId value is invalid:
{"SearchResponse":{"Version":"2.2","Query":{"SearchTerms":"xbox site\u003amicrosoft.com"},"Errors":[{"Code":1002,"Message":"Parameter has invalid value.","Parameter":"SearchRequest.AppId","Value":"*******\u002*****\u002b***","HelpUrl":"http\u003a\u002f\u002fmsdn.microsoft.com\u002fen-us\u002flibrary\u002fdd251042.aspx"}]}}
Where *** are valid characters of my account key
I tried all possible ways that came to my mind and found in web, but still failed to solve it. So what I tried:
import requests
url = "http://api.bing.net/json.aspx?AppId=****/***+***&Query=xbox site:microsoft.com&Sources=Image"
r = requests.get(url)
I got an error that the value is invalid "****\u002*** ***"
I tried doing the same thing using urllib2, trying to encode and quote both the whole query and the account key only. The code for separately quoting each part of request is like this:
import urllib2
urlStart = u"http://api.bing.net/json.aspx?AppId=%s&Query=xbox"
quotedUrlStart = urllib2.quote(urlStart.encode("utf8"), safe="%/:=&?~#+!$,;'@()*[]")
urlEnd = u" site:microsoft.com&Sources=Image"
quotedUrlEnd = urllib2.quote(urlEnd.encode("utf8"), safe="")
key = u"**/**+**"
quotedKey = urllib2.quote(key.encode("utf8") , safe="%:=&?~#!$,;'@()*[]")
fullUrl = (quotedUrlStart % quotedKey) + quotedUrlEnd
reply = urllib2.urlopen(fullUrl).read()
print reply
I also tried to replace "/" with %2F and "+" with %2B, but the error is the same. What is a mess for me here is what I have to quote and what not. I actually don't have a clear understanding so far how these things work. I guess that I have to encode everything and quote it different ways - qoute slashes in one place and do not qoute in another.
This question addresses the same issue: XCODE Swift Replacing HTTP-Get App-ID with a space Also there are numerous questions on SO on escaping symbols, but they were unhelpful for me
I appreciate your time guys