Mer*_*rin 17 c# get http download
我使用HTTP GET在浏览器中下载zip文件,例如 https://example.com/up/DBID/a/rRID/eFID/vVID(不是确切的URL)
现在,当我尝试在桌面应用程序中使用C#代码(与上面相同的GET方法)进行相同的下载时,下载的zip文件不是有效的存档文件.当我在记事本中打开此文件时,它是一些HTML页面.
我想我没有正确设置一些标题.我四处寻找例子.我发现了几个wrt上传,但没有看到任何下载.
码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/zip";
try
{
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
{
StreamWriter oWriter = new StreamWriter(@"D:\Downloads\1.zip");
oWriter.Write(sr.ReadToEnd());
oWriter.Close();
}
res.Close();
}
catch (Exception ex)
{
}
Run Code Online (Sandbox Code Playgroud)
Hen*_*man 39
这主要是因为您使用a StreamWriter : TextWriter 来处理二进制Zip文件.StreamWriter需要文本并将应用编码.甚至简单的ASCII编码器也可能试图"修复"它认为无效的行结尾.
您可以用以下代码替换所有代码:
using (var client = new WebClient())
{
client.DownloadFile("http://something", @"D:\Downloads\1.zip");
}
Run Code Online (Sandbox Code Playgroud)
你可以用WebClient一个2班轮:
using(WebClient wc = new WebClient())
{
wc.DownloadFile(url, @"D:\Downloads\1.zip");
}
Run Code Online (Sandbox Code Playgroud)