Search code examples
c#jsongoogle-search

How to make a GET REST API request to Google Custom Search API in C#


I have created a Google Custom Search which I can successfully call using the JSON/Atom Custom Search API and then load the results from it into a javascript function when I have a script tag within an aspx page:

<script src="https://www.googleapis.com/customsearch/v1?key={my key}&amp;cx={my CX code};q=Shell&amp;callback=hndlr"></script>

However, I am trying to make this GET request within C# and I can't seem to get it to work. I haven't made GET requests before in C# so I'm sure I'm making a basic error somewhere. The code I am trying is below:

System.Net.HttpWebRequest hwb;

String url = "https://www.googleapis.com/customsearch/v1?key={my key}&amp;cx={my cx code}&amp;q=Shell";

    hwb = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

    HttpWebResponse resp = (HttpWebResponse)hwb.GetResponse();

It returns the following error when the GetResponse() call is made on the final line:

"The remote server returned an error: (400) Bad Request."

Any assistance in pointing out where I'm going wrong would be much appreciated - even if it's just to confirm that this particular API can't be used in this way!


Solution

  • If what you have on the site is exactly what you're trying, replace the &amp; sequences in the URL with just &