C#中http请求下载的常用方式demo
//通过webClient方式
WebClient client = new WebClient();
string url="http://down6.3987.com:801/2010/office_3987.com.zip";
Stream strm = client.OpenRead("http://down6.3987.com:801/2010/office_3987.com.zip");
string filename=url.Substring(url.LastIndexOf('/')+1);
int count = 0;
byte[] buffer = new byte[4096];
FileStream fs = new FileStream(Application.StartupPath+"//"+filename, FileMode.Create);
while ((count = strm.Read(buffer, 0, buffer.Length)) > 0) {
fs.Write(buffer, 0, count);
}
fs.Close();
strm.Close();
strm.Dispose();
fs.Dispose();
//通过原生态HttpWebrequest方式
string url = "http://down6.3987.com:801/2010/office_3987.com.zip";
string filename = url.Substring(url.LastIndexOf('/') + 1);
//用webClient方式创建http请求
HttpWebRequest req =(HttpWebRequest)HttpWebRequest.Create(url) ; //创建链接
//获取服务其数据
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream mystream = res.GetResponseStream();
//开始文件操作
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory+"//"+filename, FileMode.Create, FileAccess.Write, FileShare.None);
byte[] buffer=new byte[1024];
int count=0;
while((count=mystream.Read(buffer,0,1024))>0)
{
fs.Write(buffer, 0, count);
}
fs.Close();
mystream.Close();
fs.Dispose();