88

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?

2
  • anyone knows why i cant get the json data? Commented Jan 22, 2010 at 9:34
  • 7
    You need using (var response = request.GetResponse()){ ... }. May not solve the problem but saves the resource leak. Commented Sep 16, 2010 at 18:55

2 Answers 2

75

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";
Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible to pass the parameter with this??
Perhaps you can try to add your parameters to requestUri I.e. localhost/api/product/123
@JidheeshRajan See this question/answers for how to add parameters to a WebRequest stackoverflow.com/questions/3279888/…
Adding only request.ContentType = "application/json; wasn't enough for me so I think your solution is the correct one.
This answer should be accepted because the current accepted answer is not correct. Another example of not using "Accept" when appropriate...
69

You need to explicitly ask for the content type.

Add this line:

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

4 Comments

Is it possible to pass the parameter with this request??
Request Content-Type describes type of request body. It is used to tell the server in what format the data is being sent to server. It has nothing to do with content type of response. The client may ask to reply with specific types using Accept header, but the server may ignore it for other reasons.
I know this is an old answer but for completeness wanted to reply to @SHEKHARSHETE: you can use something like the excellent NewtonSoft JSON.Net which will do the work for you and I recommend reading the useful guides to workout how to do this here: newtonsoft.com/json

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.