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?
You use the GetAsync method to send a GET request and then the JsonObject. Parse method to parse the returned JSON string.
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.
WebRequest is the abstract base class for . NET's request/response model for accessing data from the Internet.
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With