我有一个要求,我必须根据输入参数使用 c#(大小可以在 10mb - 400mb 之间变化)从服务器下载一个 zip 文件。例如,下载 userId = 10 和 year = 2012
的报告。网络服务器接受这两个参数并返回一个 zip 文件。如何使用 WebClient 类来实现这一点?
谢谢
问问题
5770 次
2 回答
6
您可以通过扩展 WebClient 类来做到这一点
class ExtWebClient : WebClient
{
public NameValueCollection PostParam { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest tmprequest = base.GetWebRequest(address);
HttpWebRequest request = tmprequest as HttpWebRequest;
if (request != null && PostParam != null && PostParam.Count > 0)
{
StringBuilder postBuilder = new StringBuilder();
request.Method = "POST";
//build the post string
for (int i = 0; i < PostParam.Count; i++)
{
postBuilder.AppendFormat("{0}={1}", Uri.EscapeDataString(PostParam.GetKey(i)),
Uri.EscapeDataString(PostParam.Get(i)));
if (i < PostParam.Count - 1)
{
postBuilder.Append("&");
}
}
byte[] postBytes = Encoding.ASCII.GetBytes(postBuilder.ToString());
request.ContentLength = postBytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
var stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
stream.Dispose();
}
return tmprequest;
}
}
用法:如果你必须创建 POST 类型的请求
class Program
{
private static void Main()
{
ExtWebClient webclient = new ExtWebClient();
webclient.PostParam = new NameValueCollection();
webclient.PostParam["param1"] = "value1";
webclient.PostParam["param2"] = "value2";
webclient.DownloadFile("http://www.example.com/myfile.zip", @"C:\myfile.zip");
}
}
用法:对于 GET 类型的请求,你可以简单地使用普通的 webclient
class Program
{
private static void Main()
{
WebClient webclient = new WebClient();
webclient.DownloadFile("http://www.example.com/myfile.zip?param1=value1¶m2=value2", @"C:\myfile.zip");
}
}
于 2013-01-23T08:19:02.827 回答
-1
string url = @"http://www.microsoft.com/windows8.zip";
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(url), @"c:\windows\windows8.zip");
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("File downloaded");
}
于 2013-01-23T08:24:42.703 回答