public void GetDown(string token, string fileid, string filename) { try { string edocUrl = ConfigurationManager.AppSettings["ApiServiceUrl"]; string path = System.AppDomain.CurrentDomain.BaseDirectory + "Downloads\\"; var url = string.Format("{0}Document/File_Download.aspx?regionid=1&file_id={1}&token={2}&num={3}", edocUrl, fileid, token, new Random().Next()); using (MyWebClient webClient = new MyWebClient()) { webClient.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"); using (Stream stream = webClient.OpenRead(url)) { using (FileStream fs = File.Create(path + "\\" + filename)) { int i = 0; do { byte[] buffer = new byte[1024]; i = stream.Read(buffer, 0, 1024); fs.Write(buffer, 0, i); } while (i > 0); } } } } catch (Exception ex) { WriteLog(LogType.Errors, "文件下载失败:" + "," + ex.Message); } }
如上代码,通过url下载文件,每次都是第一次可以下载下来,第二次就抛异常: 服务器提交了协议冲突. Section=ResponseStatusLine
更诡异的是,我调试代码,没有任何问题,不调试直接运行,就会抛异常!!!
请问大神这该怎么办?
public string GetDown(string token, string fileid, string filename) { try { string edocUrl = ConfigurationManager.AppSettings["ApiServiceUrl"]; string path = System.AppDomain.CurrentDomain.BaseDirectory + "Downloads\\"; var url = string.Format("{0}Document/File_Download.aspx?regionid=1&file_id={1}&token={2}&num={3}", edocUrl, fileid, token, new Random().Next()); using (WebClient webClient = new WebClient()) { webClient.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"); using (Stream stream = webClient.OpenRead(url)) { using (FileStream fs = File.Create(path + "\\" + filename)) { int i = 0; do { byte[] buffer = new byte[1024]; i = stream.Read(buffer, 0, 1024); fs.Write(buffer, 0, i); } while (i > 0); } } } } catch (Exception ex) { WriteLog(LogType.Errors, "文件下载失败:" + "," + ex.Message); } }
即使,我没有用自己写的WebClient,也是一样的问题。
还有
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing= "true " />
</settings>
</system.net>
我也加了
第一次下载和第二次下载之间间隔一点时间试试
试了一下,还真行了。。。
@慕云Love: 因为你说你调试没问题,我就觉得应该是这样。以前我做一个项目也遇到过,后来发现是网站限制了 当然也可能是网络的原因
试试 服务器提交了协议冲突.相关 终极解决方案中的方法:
request.ProtocolVersion = HttpVersion.Version10;
麻烦说详细点,在哪里加呢?
@慕云Love: 试试下面的代码:
var webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.ProtocolVersion = HttpVersion.Version10; using (var webResponse = webRequest.GetResponse()) { using (var responseSteam = webResponse.GetResponseStream()) { using (var fs = new FileStream(path + "\\" + filename, FileMode.Create)) { responseSteam.CopyTo(fs); } } }
@慕云Love: 另外,既然用了WebClient,为什么不直接用 webClient.DownloadFile() 下载文件?
建议将这里的浏览器版本换成高版本的:
webClient.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");