如何在 C# 中使用 system.net.webrequest 获取 json 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2108297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get json response using system.net.webrequest in c#?
提问by h3n
I need to get json data from an external domain. I used webrequest to get the response from a website. Here's the code:
我需要从外部域获取 json 数据。我使用 webrequest 从网站获取响应。这是代码:
var request = WebRequest.Create(url);
string text;
var response = (HttpWebResponse) request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
Anyone know why I can't get the json data?
有人知道为什么我无法获取json数据吗?
采纳答案by Oren A
You need to explicitly ask for the content type.
您需要明确要求内容类型。
Add this line:
添加这一行:
request.ContentType = "application/json; charset=utf-8";
在适当的地方回答by Martin Buberl
Some APIs want you to supply the appropriate "Accept" headerin the request to get the wanted response type.
某些 API 要求您在请求中提供适当的“接受”标头以获得所需的响应类型。
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".
例如,如果 API 可以返回 XML 和 JSON 格式的数据,而您想要 JSON 结果,则需要将该HttpWebRequest.Accept
属性设置为"application/json"。
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";