文章介绍了通过HttpWebRequest和HttpWebResponse实现视频下载的功能;首先HttpWebRequest类利用HTTP 协议和服务器交互,再由HttpWebResponse返回来自网络资源的响应,最后由stream类处理数据流,缓存到本地磁盘;
上代码之前先上一张Demo的图片,新建一个winform窗体,添加lable控件,ProgressBar和button按钮,以下仅供参考
using System;
using System.IO;
using System.Net;
using System.Windows.Forms; namespace FileDownLoad
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string URL = "https://media.w3.org/2010/05/sintel/trailer.mp4";//视频网络地址
string filename = @"D:\视频下载\\video.mp4";//存储视频的文件地址
DownloadFile(URL, filename, progressBar1);//调用下载方法
}
/// <summary>
/// 下载视频
/// </summary>
/// <param name="URL">请求地址</param>
/// <param name="filename">缓存的路径</param>
/// <param name="prog">进度条</param>
public void DownloadFile(string URL, string filename, ProgressBar prog)
{
try
{
float percent = ;
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(URL);//请求网络资源
HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();//返回Internet资源的响应
long totalBytes = myrp.ContentLength;//获取请求返回内容的长度
if (prog != null)
{
prog.Maximum = (int)totalBytes;//获取进度条的最大值
}
Stream st = myrp.GetResponseStream();//读取服务器的响应资源,以IO流的形式进行读写
Stream so = new FileStream(filename, FileMode.Create);
long totalDownloadedByte = ;
byte[] by = new byte[];
int osize = st.Read(by, , (int)by.Length);
while (osize > )
{
totalDownloadedByte = osize + totalDownloadedByte;
Application.DoEvents();//交出CPU控制权,让系统可以处理队列中的所有Windows消息 ,防止频繁读写造成程序阻塞或界面停止响应
so.Write(by, , osize);
if (prog != null)
{
prog.Value = (int)totalDownloadedByte;
}
osize = st.Read(by, , (int)by.Length);//读取当前字节流的总长度
percent = (float)totalDownloadedByte / (float)totalBytes * ;
double perNumber = Math.Round(percent);
label1.Text = "系统更新已完成:" + perNumber.ToString() + "%";
Application.DoEvents();//此处是为了防止lable1的内容来不及显示
}
so.Flush();
so.Close();
st.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
代码完成,实现下载功能,具体Demo请点击文末链接
点击下载 提取码:yg4g