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?

fat
  • 6,435
  • 5
  • 44
  • 70
h3n
  • 5,142
  • 9
  • 46
  • 76

2 Answers2

76

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";
Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
  • 1
    Is it possible to pass the parameter with this?? – Jidheesh Rajan Oct 10 '13 at 06:31
  • Perhaps you can try to add your parameters to `requestUri` I.e. localhost/api/product/123 – NoWar Jan 03 '14 at 14:35
  • @JidheeshRajan See this question/answers for how to add parameters to a `WebRequest` http://stackoverflow.com/questions/3279888/how-to-add-parameters-into-a-webrequest – Martin Buberl Jan 03 '14 at 15:24
  • 1
    Adding only request.ContentType = "application/json; wasn't enough for me so I think your solution is the correct one. – Campinho Oct 20 '15 at 01:26
  • This answer should be accepted because the current accepted answer is not correct. Another example of not using "Accept" when appropriate... – Arkaine55 Jun 14 '16 at 18:55
70

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place
Oren A
  • 5,870
  • 6
  • 43
  • 64
  • Is it possible to pass the parameter with this request?? – Jidheesh Rajan Oct 10 '13 at 06:37
  • 7
    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. – temoto Mar 18 '14 at 13:13
  • Yes Jidheesh, see this http://stackoverflow.com/questions/10263082/how-to-pass-post-parameters-to-asp-net-web-request – Zameer Ansari May 14 '14 at 09:45
  • 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: http://www.newtonsoft.com/json – Trevor Oct 17 '16 at 01:44