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;

}

相关推荐
23.1 小时前
【网络】TCP与HTTP:网络通信的核心机制解析
网络·tcp/ip·http
独自破碎E1 小时前
【面试真题拆解】5秒内限10次HTTP接口访问,结合数据结构和算法说说你的思路
数据结构·http·面试
小庄梦蝶2 小时前
Mixed Content: The page at ‘https://域名/‘ was loaded over HTTPS
网络协议·http·https
带娃的IT创业者2 小时前
Weclaw 混合通讯架构实战:HTTP+SSE+WebSocket的三元融合如何支撑起整个 AI 助手的实时对话?
websocket·http·fastapi·sse·流式响应·实时通讯·混合架构
长安110817 小时前
web后端----HTTP协议与浏览器F12
前端·网络协议·http
Java成神之路-19 小时前
HTTP 协议进化史:从 1.0 到 3.0
网络·网络协议·http
魑魅魍魉都是鬼1 天前
TCP、UDP Http Https
tcp/ip·http·udp
tzy2331 天前
HTTPS 认证过程
网络协议·http·https
nainaire1 天前
仿muduo库的Tcp服务器以及其应用层Http协议支持
服务器·网络·c++·tcp/ip·http
森叶1 天前
深入理解 Hash:它不是一个函数,而是一种思想
人工智能·http·架构