通过http通讯下载资源

var localFilePath = config.GetValue("ftp:downAddress") + fileName;

Logger.Main.Info("[保存的文件为]"+localFilePath);
HttpWebRequest reqHttp;

//创建本地文件流,用于写入数据
FileStream outputStream = new FileStream(localFilePath, FileMode.Create);

//获取目标地址的目标资源
reqHttp = (HttpWebRequest)WebRequest.Create(new Uri(filePath));
reqHttp.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)reqHttp.GetResponse();

Stream httpStream = response.GetResponseStream();

//构建写入数据流参数
long cl = response.ContentLength;

int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = httpStream.Read(buffer, 0, bufferSize);//返回值为实际写入缓存区字节数
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);//写入字节流
outputStream.Flush();//写入缓存中的流数据
readCount = httpStream.Read(buffer, 0, bufferSize);
}
httpStream.Close();
outputStream.Close();
response.Close();
return localFilePath;

学习中,若有不足,欢迎各位大佬指点

posted @ 2020-11-19 13:52  土豆2号  阅读(136)  评论(0编辑  收藏  举报