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;

}

相关推荐
Dovis(誓平步青云)1 天前
《Linux生态下HTTP协议解析+进阶HTTPS证书:抓包、拆解与问题排查实战》
linux·运维·http
Boop_wu1 天前
[Java EE] 网络原理(2) http
网络·网络协议·http
大布布将军1 天前
⚡️编排的艺术:BFF 的核心职能——数据聚合与 HTTP 请求
前端·网络·网络协议·程序人生·http·node.js·改行学it
Bruce_Liuxiaowei2 天前
网站敏感文件_目录大全(分类记忆+风险标注)
运维·网络·网络协议·http·网络安全·https
charlee442 天前
使用cpp-httplib发布HTTP服务
c++·http·json·cpp-httplib
爬山算法2 天前
Netty(22)如何实现基于Netty的HTTP客户端和服务器?
服务器·网络协议·http
爱吃香蕉的阿豪2 天前
NET Core中ConcurrentDictionary详解:并发场景下的安全利器及服务端实践
安全·http·.netcore·高并发
小阿宁的猫猫3 天前
CSRF漏洞的原理、防御和比赛中的运用
安全·http·xss·csrf
教练、我想打篮球3 天前
120 同样的 url, header, 参数, 使用 OkHttp 能够成功获取数据, 使用 RestTemplate 报错
http·okhttp·resttemplate·accept
zfj3213 天前
websocket为什么需要在tcp连接成功后先发送一个标准的http请求,然后在当前tcp连接上升级协议成websocket
websocket·tcp/ip·http