Search code examples
c#google-search-api

Error 404 from Google Search API


I'm getting a 404 error from the code below. I'm running Visual C# Express 2010. The query portion of the string is:

q%3dAction%2bMotivation%2c%2bInc.%2bSouth%2bSan%2bFrancisco%2b%26alt%3djson%26start%3d0%26num%3d10"

string searchString =       
    "https://www.googleapis.com/customsearch/v1%3fkey%3d{APIkey}%26cx%3d{cxkey}%26q%3dAction%2bMotivation%2c%2bInc.%2bSouth%2bSan%2bFrancisco%2b%26alt%3djson%26start%3d0%26num%3d10";
WebRequest myRequest = WebRequest.Create(searchString);
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

Solution

  • You're escaping far too much. You should only escape the query value - not the key/value pair separators. So the URL should be something like:

    string url = string.Format(
        "https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}",
        HttpUtility.UrlEncode(apiKey),
        HttpUtility.UrlEncode(cxKey),
        HttpUtility.UrlEncode(query));
    

    (Where query is the original query, e.g. "Action Motivation Inc." (I haven't checked what the escape sequences you're using actually represent.)