private async void 下载保存测试股票数据文件(string stockCode)
{
//设定下载时间段
DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddDays(-30);
string filePathName = "C:\\TEMP\\" + stockCode + ".csv";
string uri = string.Format("http://quotes.money.163.com/service/chddata.html?code={0}&start={1}&end={2}&fields=TCLOSE;HIGH;LOW;TOPEN;TURNOVER;VOTURNOVER", stockCode, startDate.ToString("yyyyMMdd"), endDate.ToString("yyyyMMdd"));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
using (StreamReader srWeb = new StreamReader(responseStream, Encoding.GetEncoding("gb2312")))
{
string text = await srWeb.ReadToEndAsync();
//或者取消异步直接string text = srWeb.ReadToEnd();
//或者循环读取一行While(text = srWeb.ReadLine() != null)
Console.WriteLine(text);
}
}
//即使使用ReadLine(),第一次有一行数据,第二次读行就为空了,啥道理啊?困住了,大家能否救救我,跪谢!
//用uri的实际字符串手动在浏览器里能直接下载到完整的多行数据,比如:
http://quotes.money.163.com/service/chddata.html?code=0601336&start=20160616&end=20160716&fields=TCLOSE;HIGH;LOW;TOPEN;TURNOVER;VOTURNOVER
找到问题答案了,问题出在这句:
string uri = string.Format("http://quotes.money.163.com/service/chddata.html?code={0}&start={1}&end={2}&fields=TCLOSE;HIGH;LOW;TOPEN;TURNOVER;VOTURNOVER", stockCode, startDate.ToString("yyyyMMdd"), endDate.ToString("yyyyMMdd"));
把code={0}改为code=0{0}即可,原来对网址规则没分析清楚。
用fiddler调试下看看
string text = await srWeb.ReadToEndAsync();
得到的应该就是整个文件变成的String,如果想获得List< String >的话,试试
```var fileText = await reader.ReadToEndAsync();return fileText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
出处:[http://stackoverflow.com/questions/13167934/how-to-async-files-readalllines-and-await-for-results](http://stackoverflow.com/questions/13167934/how-to-async-files-readalllines-and-await-for-results "")
估计是和异步读写有关吧
using (StreamReader srWeb = new StreamReader(responseStream, Encoding.GetEncoding("gb2312")))
{
String line;
while ((line = srWeb.ReadLine()) != null)
{
sw.WriteLine(line);
}
}