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;

}

相关推荐
Mu.38715 分钟前
计算机网络模型
网络·网络协议·计算机网络·安全·http·https
我有一棵树30 分钟前
file 协议与 http 协议的区别:为什么本地 HTML 无法加载相对路径 JS,以及正确的解决方式
javascript·http·html
阿珊和她的猫1 天前
HTTP 状态码 301 和 302 的区别与使用场景
网络·网络协议·http
6***94151 天前
报错The default superclass, “jakarta.servlet.http.HttpServlet“(已经配置好tomcat)
http·servlet·tomcat
记得记得就1511 天前
【Nginx 实战系列(一)—— Web 核心概念、HTTP/HTTPS协议 与 Nginx 安装】
前端·nginx·http
阿珊和她的猫2 天前
HTTP 状态码 304:未修改(Not Modified)的深度解析
网络协议·http·状态模式
chuxinweihui2 天前
应用层协议 HTTP
linux·服务器·网络·网络协议·http
chuxinweihui2 天前
HTTP cookie 与 session
网络·网络协议·http
RocketJ2 天前
TCP、Telepathy 和 HTTP 三者关系
网络协议·tcp/ip·http
默恋~微凉2 天前
Shell(九)——HTTP与HTTPS协议
网络协议·http·https