C#利用HttpClient实现反向代理分块下载
最近遇到的一个项目,附件在A服务器,对外是B服务器,A与B服务器可以内网通信,但是A服务器不对外,就需要用到B服务器的对外访问地址浏览附件与文件,参考了部分网上的代码,附上函数
/// <summary>
/// 异步下载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void FileDownloadAsync(string url)
{
//开启一个异步线程
await System.Threading.Tasks.Task.Run(async () =>
{
long downloadSize = 0;//已经下载大小
long downloadSpeed = 0;//下载速度
using (HttpClient http = new HttpClient())
{
var httpResponseMessage = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);//发送请求
var contentLength = httpResponseMessage.Content.Headers.ContentLength; //文件大小
string contentType = httpResponseMessage.Content.Headers.ContentType.MediaType??MimeMapping.GetMimeMapping(url);
string fileName = httpResponseMessage.Content.Headers.ContentDisposition!=null?httpResponseMessage.Content.Headers.ContentDisposition.FileName:Path.GetFileName(url);
//兼容各种URL文件
if (fileName.IsNull())
fileName = Path.GetFileName(url);
using (var stream = await httpResponseMessage.Content.ReadAsStreamAsync())
{
var readLength = 102400;//100K
byte[] bytes = new byte[readLength];
int writeLength;
var beginSecond = DateTime.Now.Second;//当前时间秒
Response.Clear();
Response.ContentType = "application/octet-stream"; //二进制流
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));//下载保存的文件名
Response.AddHeader("Content-Length", contentLength.HasValue?contentLength.Value.ToString():"0");//文件总大小
while ((writeLength = stream.Read(bytes, 0, readLength)) > 0)
{
if (Response.IsClientConnected)
{
Response.OutputStream.Write(bytes, 0, writeLength);
Response.Flush();//如果客户端 暂停下载时,这里会阻塞。
}
downloadSize += writeLength;
downloadSpeed += writeLength;
}
Response.Close();
}
}
});
}
浙公网安备 33010602011771号