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

h3n*_*h3n 77 .net c# json webrequest

我需要从外部域获取json数据.我使用webrequest来获取网站的回复.这是代码:

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

using (var sr = new StreamReader(response.GetResponseStream()))
{
    text = sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么我不能得到json数据?

Mar*_*erl 71

某些API希望您在请求中提供适当的"Accept"标头以获取所需的响应类型.

例如,如果API可以返回XML和JSON中的数据,并且您需要JSON结果,则需要将该HttpWebRequest.Accept属性设置为"application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
Run Code Online (Sandbox Code Playgroud)

  • 好方案! (4认同)

Ore*_*n A 64

您需要明确询问内容类型.

添加此行:

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

  • 请求Content-Type描述请求正文的类型.它用于告诉服务器数据以何种格式发送到服务器.它与内容类型的响应无关.客户端可能会要求使用"Accept"标头回复特定类型,但服务器可能会因其他原因忽略它. (6认同)