我需要从外部域中获取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数据吗?

有帮助吗?

解决方案

您需要明确要求内容类型。

添加此行:

 request.ContentType = "application/json; charset=utf-8";
在适当的地方

其他提示

一些API希望您提供 适当的“接受”标题 在获得通缉响应类型的请求中。

例如,如果API可以在XML和JSON中返回数据,并且您需要JSON结果,则需要设置 HttpWebRequest.Accept 财产为 “应用程序/JSON”.

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top