C#使用HttpWebRequest下载文件

public static bool HttpDownloadFile(string downloadUrl, string localPath, log4net.ILog log)

{

bool bFlagDownloadFile = false;

//log.Debug("HttpDownloadFile--准备以HTTP的方式下载文件,url:[" + downloadUrl + "]本地文件:【" + localPath + "】");

HttpWebRequest request = null;

HttpWebResponse resp = null;

try

{

request = WebRequest.Create(downloadUrl) as HttpWebRequest;

request.Timeout = 3000;

//log.Info("HttpDownloadFile--新建HttpWebRequest!");

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });

resp = request.GetResponse() as HttpWebResponse;

string responseCode = string.Empty;

//获得http响应状态

bFlagDownloadFile = getResponseResult(resp.StatusCode, ref responseCode);

//获得HTTP响应的接收流

Stream ns = resp.GetResponseStream();

FileStream fs;

fs = new FileStream(localPath, System.IO.FileMode.Create);

int totalFileLen = 0; //文件最多支持2^32 = 4G

int fileBufferSize = 1024;

byte[] nbytes = new byte[fileBufferSize];

int nreadsize = ns.Read(nbytes, 0, fileBufferSize);

while (nreadsize > 0)

{

fs.Write(nbytes, 0, nreadsize);

totalFileLen += nreadsize;

nreadsize = ns.Read(nbytes, 0, fileBufferSize);

}

fs.Close();

ns.Close();

bFlagDownloadFile = true;

try

{

if (resp != null)

{

resp.Close();

resp = null;

}

}

catch (Exception e)

{

}

try

{

if (request != null)

{

request.Abort();

request = null;

}

}

catch (Exception e)

{

}

log.Debug("HttpDownloadFile--以HTTP的方式下载文件,本地文件:【" + localPath + "】成功!");

}

catch (Exception ex)

{

log.Error("HttpDownloadFile--以HTTP的方式下载文件,本地文件:【" + localPath + "】时发生错误!异常消息:" + ex.Message,ex);

bFlagDownloadFile = false;

try

{

if (resp != null)

{

resp.Close();

resp = null;

}

}catch(Exception e)

{

}

try

{

if (request != null)

{

request.Abort();

request = null;

}

}

catch (Exception e)

{

}

}

return bFlagDownloadFile;

}

相关推荐
liulovesong21 小时前
2024/06/21/第三天
http·echarts
win x1 天前
深入理解HTTPS协议加密流程
网络协议·http·https
仙俊红1 天前
从 Filter / Interceptor 到 HTTPS
网络协议·http·https
liann1191 天前
3.1_网络——基础
网络·安全·web安全·http·网络安全
三水不滴2 天前
计算机网络核心网络模型
经验分享·笔记·tcp/ip·计算机网络·http·https
SunflowerCoder2 天前
基于插件化 + Scriban 模板引擎的高效 HTTP 协议中心设计
http·c#
Remember_9932 天前
MySQL 索引详解:从原理到实战优化
java·数据库·mysql·spring·http·adb·面试
Zach_yuan2 天前
从零理解 HTTP:协议原理、URL 结构与简易服务器实现
linux·服务器·网络协议·http
JQLvopkk2 天前
C# 实现Http Json格式 Post 、Get 方法请求 winform服务器
http·c#·json
csdn2015_3 天前
Spring Boot `HttpServletRequest`
spring boot·http·servlet