使用C#停止使用yahoo finace api后获取库存数据

时间:2017-07-14 20:42:55

标签: c# yahoo-finance

我正在尝试使用cookie和crumb以新的方式获取库存数据,但我无法让它工作。

Stream data;
StreamReader reader;
String html;
WebClient webClient;
String url;

webClient = new WebClient();
url = "https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval=1d&events={3}&crumb={4}";
webClient.Headers.Add("user-agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11");
data = webClient.OpenRead("https://finance.yahoo.com/quote/%5EGSPC");
reader = new StreamReader (data);
String crumbPattern = "\"CrumbStore\":{\"crumb\":\"(?<crumb>[^\"]+)\"}";
html = reader.ReadToEnd();
Match mCrumb = Regex.Match(html, crumbPattern);
currentCrumb = mCrumb.Value.Substring(24, mCrumb.Value.Length - 26);

int tmpS = 1494817200;
int tmpE = 1498928400;
data = webClient.OpenRead(String.Format(url, "O", tmpS, tmpE, "history", currentCrumb));
reader = new StreamReader (data);
html = reader.ReadToEnd();

但这不起作用,当我运行时,我得到一个未经授权的例外。

The remote server returned an error: (401) Unauthorized.

有人能看出我做错了吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

您正在检索的currentCrumb看起来不完整。它截断了第一个字符。这对我有用。

        Stream data;
        StreamReader reader;
        String html;
        WebClient webClient;
        String url;

        webClient = new WebClient();
        url = "https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval=1d&events={3}&crumb={4}";
        webClient.Headers.Add("user-agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11");
        data = webClient.OpenRead("https://finance.yahoo.com/quote/%5EGSPC");

        string cookie = webClient.ResponseHeaders["Set-Cookie"];

        reader = new StreamReader(data);
        String crumbPattern = "\"CrumbStore\":{\"crumb\":\"(?<crumb>[^\"]+)\"}";
        html = reader.ReadToEnd();
        Match mCrumb = Regex.Match(html, crumbPattern);
        string[] strs = mCrumb.Value.Split(':');
        string currentCrumb = strs[2].Substring(1, strs[2].Length - 3);

        int tmpS = 1494817200;
        int tmpE = 1498928400;
        webClient.Headers.Add("Cookie", cookie);
        data = webClient.OpenRead(String.Format(url, "O", tmpS, tmpE, "history", currentCrumb));
        reader = new StreamReader(data);
        html = reader.ReadToEnd();

答案 1 :(得分:0)

您似乎没有正确设置会话的Cookie。您被拒绝是因为该服务无法找到其使用的凭据。

你在评论中说过你试过:

webClient.Headers.Add("Set-Cookie", webClient.ResponseHeaders["Set-Cookie"]);

但这是无效的:Set-Cookie指令由服务器发送,不应由客户端在查询中发送。而是尝试:

webClient.Headers.Add("Cookie", webClient.ResponseHeaders["Set-Cookie"]);

有关Set-Cookie的更多信息:HTTP Cookies - Mozilla

如果这不起作用,也许您应该查看Authentication at Yahoo上的文档,但不幸的是,为OAuth和OpenID提供的链接将转到404 ...

雅虎船正在下沉......无法帮助你。