1、问题原因 新浪股票接口返回如标题所示值:Kinsoku jikou desu! http://hq.sinajs.cn/list=code新浪股票的接口变动,需要在请求头中添加Referer值。 数据源网站:新浪财经_新浪网 2、核
1、问题原因
新浪股票接口返回如标题所示值:Kinsoku jikou desu!
http://hq.sinajs.cn/list=code 新浪股票的接口变动,需要在请求头中添加Referer值。
数据源网站:新浪财经_新浪网
2、核心代码
/// <summary>
/// 获取新浪股票缓存
/// </summary>
/// <param name="args">请求查询的代码</param>
/// <returns></returns>
[HttpGet, HttpPost]
public string GetSinaStockCache(string args)
{
string url = "http://hq.sinajs.cn/list=" + args;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); // 创建一个请求示例
// .NET Core版本
request.Headers.Add("Referer", "https://finance.sina.com.cn/");
// .NET Framework版本
// request.Referer = "https://finance.sina.com.cn/";
HttpWebResponse response = (HttpWebResponse) request.GetResponse(); // 获取响应,即发送请求
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.Default); // Default中文正常显示,UTF-8中文会乱码
string json = streamReader.ReadToEnd();
return json;
}
为了避免接口变动,可以在获取响应值时写入缓存,给缓存一个有效期,只要返回信息异常就读取缓存即可。
最后感谢新浪股票接口一直以来的稳定支持和大神的先见之明。
3、测试
请求参数(args):sz000651
返回结果:
"var hq_str_sz000651=\"格力电器,39.300,39.220,38.640,39.300,38.520,38.640,38.640,42165560,1634520898.300,465667,38.640,57333,0.000,0,0.000,0,0.000,0,0.000,465667,38.640,0,0.000,0,0.000,0,0.000,0,0.000,2022-02-17,14:59:06,00\";\n"