Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 888
h3n Avatar asked Jan 21 '10 10:01

h3n


People also ask

How to parse JSON request in c#?

You use the GetAsync method to send a GET request and then the JsonObject. Parse method to parse the returned JSON string.

How do I reply to WebRequest?

The GetResponse method sends a request to an Internet resource and returns a WebResponse instance. If the request has already been initiated by a call to GetRequestStream, the GetResponse method completes the request and returns any response. The GetResponse method provides synchronous access to the WebResponse.

What is System Net WebRequest?

WebRequest is the abstract base class for . NET's request/response model for accessing data from the Internet.

What is WebResponse?

WebResponse is the base class from which protocol-specific response classes, such as HttpWebResponse , are derived. Classes that derive from WebResponse are required to override the following members in the WebResponse class: System. Net.


1 Answers

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"; 
like image 155
Martin Buberl Avatar answered Oct 07 '22 03:10

Martin Buberl