开发者

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

开发者 https://www.devze.com 2022-12-18 04:00 出处:网络
I need to get json data from an external domain. I used WebRequest开发者_Python百科 to get the response from a website.

I need to get json data from an external domain.

I used WebRequest开发者_Python百科 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?


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


You need to explicitly ask for the content type.

Add this line:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号