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

C#.NetJsonWebrequest

C# Problem Overview


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();
}

Does anyone know why I can't get the json data?

C# Solutions


Solution 1 - C#

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";

Solution 2 - C#

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionh3nView Question on Stackoverflow
Solution 1 - C#Martin BuberlView Answer on Stackoverflow
Solution 2 - C#Oren AView Answer on Stackoverflow