https://xxx.mp4?=ig8euxZM2rNcNbN37wdVxxxx
https://xxx/?mime_type=video_mp4.mp4
怎么下载Content-Type:video/mp4 的链接视频文件
httpWebRequest下载mp4文件
直接请求
if (nurl.EndsWith("mp4")|| nurl.Contains("mp4"))
{
var savepath = Sharing.StartupPath()+this.getFileName()+".mp4";
var mp4Bytes = HTTP.GetMP4ContentAsync(nurl);
if (mp4Bytes != null && mp4Bytes.Result.Length > 0)
{
try
{
File.WriteAllBytes(savepath, mp4Bytes.Result);
Console.WriteLine("MP4 文件保存成功: " + savepath);
Widget.Ssp.Invoke(Form1.PSetTxt, new object[]
{
1,
"MP4 文件保存成功!"
});
return;
}
catch (Exception ex)
{
Console.WriteLine("保存文件时出错: " + ex.Message);
}
}
else
{
Console.WriteLine("未能获取到有效的 MP4 文件内容。");
}
return;
}
public static async Task<byte[]> GetMP4ContentAsync(string strUrl, string cookie = "", int nTimeOut = 9000)
{
if (string.IsNullOrEmpty(strUrl))
{
return null;
}
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
Util.SetCertificatePolicy();
byte[] contentBytes = null;
try
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(strUrl);
httpWebRequest.Timeout = nTimeOut;
httpWebRequest.ReadWriteTimeout = 60000;
httpWebRequest.AllowAutoRedirect = true;
if (!string.IsNullOrEmpty(cookie))
{
httpWebRequest.Headers.Add("Cookie", cookie);
}
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (Stream responseStream = httpWebResponse.GetResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] buffer = new byte[4096];
int bytesRead;
long totalBytesRead = 0;
long totalBytes = httpWebResponse.ContentLength; // 总字节数
// 读取响应流并写入内存流
while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await memoryStream.WriteAsync(buffer, 0, bytesRead);
// 计算并报告进度
totalBytesRead += bytesRead;
//if (progress != null)
//{
double percentage = (double)totalBytesRead / totalBytes * 100;
//Widget.Ssp.Invoke(Form1.PSetTxt, new object[]
//{
//3,
//Math.Round(percentage, 1).ToString("0.00") + "%"
//});
//Widget.totalProgressBar.Value = (int)percentage;
// progress.Report((int)percentage);
//}
}
contentBytes = memoryStream.ToArray();
}
}
}
catch (Exception ex)
{
HTTP.lastError = ex.Message;
}
finally
{
if (httpWebRequest != null)
{
httpWebRequest.Abort();
}
if (httpWebResponse != null)
{
httpWebResponse.Close();
}
}
return contentBytes;
}
如果出现内存泄漏可以 流式写入
-
内存流大小限制:使用
MemoryStream
类来存储下载的内容。如果下载的文件非常大(例如几个GB),那么尝试将整个文件存储在内存中可能会导致OutOfMemoryException
。尤其是在 32 位应用程序中,可用内存受到更严格的限制。 -
大文件处理: 如果下载的文件过大,例如几个 GB 的视频文件,尝试将其整个内容读取到内存中可能会导致
OutOfMemoryException
。