How to get json response using system.net.webrequest in c#?

h3n picture h3n · Jan 21, 2010 · Viewed 150.2k times · Source

I need to get json data from an external domain. I used webrequest to get the response from a website. Here's the code:

var request = WebRequest.Create(url);
string text;
var response = (HttpWebResponse) request.GetResponse();

using (var sr = new StreamReader(response.GetResponseStream()))
{
    text = sr.ReadToEnd();
}

Anyone know why I can't get the json data?

Answer

Martin Buberl picture Martin Buberl · Mar 4, 2011

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";