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 bytefileBufferSize;

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;

}

相关推荐
杨凯凡7 小时前
Spring Framework 7 HTTP Interface 实战:声明式 RestClient、超时与测试
java·spring·http
CodeYp20199 小时前
第11讲:应用层协议 HTTP
linux·http
Thanks_ks1 天前
HTTP 请求方法与 RESTful 接口设计:GET 和 POST 到底怎么用
http·api·restful·状态码·get·post·接口设计
LK_072 天前
【FastAPI】基础篇 01|开始之前:API、HTTP 与 FastAPI 到底是什么
网络协议·http·fastapi
阿星_2 天前
pydio登陆不了分析问题
网络协议·http·https
Joy T2 天前
Gzip 压缩原理与实践:HTTP 响应压缩、性能收益与工程配置
网络·网络协议·http
xixingzhe25 天前
AI 对话打字机效果:SSE 和 HTTP 的区别与适用场景
网络·网络协议·http
AI 编程助手GPT6 天前
curl 返回成功就能收文件?用本地 HTTP 验证错误页与超时
网络·网络协议·http
apollo_qwe6 天前
接口超时了,前端为什么不能直接重试?
javascript·http
Yves..7 天前
HTTP 协议学习笔记:从报文结构到抓包实践
网络协议·http·fiddler