如何在 c # 中使用 system.net.webrequest 获得 json 响应?

我需要从外部域获得 Json数据。
我使用 WebRequest从一个网站得到响应。
密码是这样的:

var request = WebRequest.Create(url);
string text;
var response = (HttpWebResponse) request.GetResponse();


using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}

有人知道我为什么拿不到 Json数据吗?

157644 次浏览

You need to explicitly ask for the content type.

Add this line:

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

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