C#根据输入参数从url下载zip文件

时间:2013-01-23 08:13:52

标签: c# download http-post

我有一个要求,我必须根据输入参数使用c#(大小可以在10mb到400mb之间)下载一个zip文件。例如,下载userId = 10和year = 2012的报告 Web服务器接受这两个参数并返回一个zip文件。如何使用WebClient类实现此目的?
感谢

2 个答案:

答案 0 :(得分: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类型请求,您只需使用Normal webclient

即可
class Program
{
    private static void Main()
    {
        WebClient webclient = new WebClient();

        webclient.DownloadFile("http://www.example.com/myfile.zip?param1=value1&param2=value2", @"C:\myfile.zip");
    }
}

答案 1 :(得分:-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");
}