文章目录
一、前言
本文介绍C#网络请求,包括Get请求、Post请求、文件上传、文件下载,一起来看看吧!
二、GET请求与POST请求
2.1 HttpWebRequest 与 HttpWebResponse
.Net中有两个类 HttpWebRequest 和HttpWebResponse 类来实现Http的请求
实现步骤:
1.通过WebRequest类创建一个HttpWebRequest的对象,该对象可以包含Http请求信息。
2.设置HttpWebRequest对象,其实就是设置Http请求报文的信息内容。
3.从HttpWebRequest对象中获取HttpWebResponse对象,该对象包含Http响应信息。
4.从响应信息中获取响应头信息和响应主体信息。
2.2 GET请求与POST请求
HTTP定义了与服务器交互的不同方法,基本方法有GET,POST,PUT,DELETE,分别对于查,该,增,删。但是,一般情况下我们只用到GET和POST。
POST与GET的差异:
GET请求 | POST请求 |
---|---|
从服务器上获取数据 | 向服务器传送数据 |
把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到 | 通过HTTPPOST机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址,用户看不到这个过程 |
服务器端用Request.QueryString获取变量的值 | 服务器端用Request.Form获取提交的数据 |
传送的数据量较小,不能大于2KB(这主要是因为受URL长度限制,因为传送的参数就放在URL后面) | 传送的数据量较大,一般被默认为不受限制。但理论上,限制取决于服务器的处理能力 |
安全性较低 | 安全性较高 |
2.3 GET请求具体实现
注意1:下面的GET请求都是带token,如果不需要token就把参数token去掉并删去设置请求头token即可
注意2:下面的网络请求都用异步包了一层,想用同步就直接调用,想用异步就调用异步。
2.3.1 GET请求仅返回网络请求成功/请求失败
#region Get请求 直接返回bool,返回false表示GET请求失败,返回true表示GET请求成功
public static bool _myGetReturnbool(string strURL, string token) //不同的get请求 地址不同所以用参数传递 token放在请求头中
//关于返回值 返回为bool
{
System.Net.HttpWebRequest request;
// 创建一个HTTP请求
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Headers["Authorization"] = "X-Token=" + token; //token放入请求头中 token用于单点登录,无此要求可省略
request.Method = "get"; // 默认为get
System.Net.HttpWebResponse response; //响应
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
JObject Data_new = (JObject)JsonConvert.DeserializeObject(responseText);
if (response.StatusCode == HttpStatusCode.OK)
{
return true;
}
return false;
}
public static Task<bool> _myGetReturnboolAsync(string strURL, string token)
{
var task = new Task<bool>(() => _myGetReturnbool(strURL, token)); //参数为委托
task.Start();
return task;
}
#endregion
2.3.2 GET请求返回网络请求成功/请求失败及返回值bool判断
#region Get请求 根据responseText返回对应值,返回-1表示Get请求失败,返回1表示Get请求成功,某一返回参数不正确,返回0表示Get请求成功,返回参数正确
public static int _myGetReturnInt(string strURL, string token) //不同的get请求 地址不同所以用参数传递 token放在请求头中
{
try
{
System.Net.HttpWebRequest request;
// 创建一个HTTP请求
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Headers["Authorization"] = "X-Token=" + token; //token放入请求头中
request.Method = "get"; // 默认为get
System.Net.HttpWebResponse response; //响应
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
JObject Data_new = (JObject)JsonConvert.DeserializeObject(responseText);
if (response.StatusCode == HttpStatusCode.OK)
{
if ("false".Equals(Data_new["Data"] + "", StringComparison.OrdinalIgnoreCase))
{
return 1;
}
if ("true".Equals(Data_new["Data"] + "", StringComparison.OrdinalIgnoreCase))
{
return 0;
}
}
return -1;
}
catch
{
//这里没什么重要的,返回-1就好了
return -1;
}
}
public static Task<int> _myGetReturnIntAsync(string strURL, string token)
{
var task = new Task<int>(() => _myGetReturnInt(strURL, token)); //参数为委托
task.Start();
return task;
}
#endregion
2.3.3 GET请求返回网络请求成功/请求失败及响应值
#region Get请求 返回responseText字符串
public static string _myGetReturnString(string strURL, string token) //不同的get请求 地址不同所以用参数传递 token放在请求头中
//关于返回值 返回为bool
{
try
{
System.Net.HttpWebRequest request;
// 创建一个HTTP请求
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Headers["Authorization"] = "X-Token=" + token; //token放入请求头中
request.Method = "get"; // 默认为get
System.Net.HttpWebResponse response; //响应
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
return responseText;
}
catch
{
//这里没什么重要的,返回-1就好了
return "-1";
}
}
public static Task<string> _myGetReturnStringAsync(string strURL, string token)
{
var task = new Task<string>(() => _myGetReturnString(strURL, token)); //参数为委托
task.Start();
return task;
}
#endregion
2.4 POST请求具体实现
2.4.1 Post请求 无参数 (默认ContentType为null)
#region post请求,无参数,无token
public static string Post(string strURL)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
req.Method = "POST";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
public static Task<string> PostAsync(string strURL)
{
var task = new Task<string>(() => Post(strURL)); //参数为委托
task.Start();
return task;
}
#endregion
#region post请求,无参数 带token
public static string _Post(string strURL, string token)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
req.Method = "POST";
req.Headers["Authorization"] = "X-Token=" + token;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
public static Task<string> _PostAsync(string strURL, string token)
{
var task = new Task<string>(() => _Post(strURL, token)); //参数为委托
task.Start();
return task;
}
#endregion
2.4.2 Post请求 用键值对dic设置请求参数
这里因为要提交数据,所以要设置ContentType,键值对设置为application/x-www-form-urlencoded。
#region post 请求,token放在请求头,返回bool 参数使用键值对dic传入
public static bool _myPost(string strURL, string token, Dictionary<string, object> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
req.Method = "POST";
req.Headers["Authorization"] = "X-Token=" + token; //token放入请求头中
req.ContentType = "application/x-www-form-urlencoded"; //表单参数
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
if (resp.StatusCode == HttpStatusCode.OK)
return true;
return false;
}
public static Task<bool> _myPostAsync(string strURL, string token, Dictionary<string, object> dic)
{
var task = new Task<bool>(() => _myPost(strURL, token, dic)); //参数为委托
task.Start();
return task;
}
#endregion
2.4.2附 Post请求 用键值对设置请求参数,变为Json数据格式
这里因为要提交数据,所以要设置ContentType,json设置为application/json。
#region post请求,token放在请求头,返回bool
public static bool _myPostJson(string strURL, string token, Dictionary<string, object> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
req.Method = "POST";
req.Headers["Authorization"] = "X-Token=" + token; //token放入请求头中
req.ContentType = "application/json;charset=UTF-8"; //使用json 这个contentType要修改
#region 添加Post 参数
string Contentjson = JsonConvert.SerializeObject(dic);
byte[] data = Encoding.UTF8.GetBytes(Contentjson);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
if (resp.StatusCode == HttpStatusCode.OK)
return true;
return false;
}
public static Task<bool> _myPostJsonAsync(string strURL, string token, Dictionary<string, object> dic)
{
var task = new Task<bool>(() => _myPostJson(strURL, token, dic)); //参数为委托
task.Start();
return task;
}
#endregion
2.4.3 Post请求 用string设置请求参数
这里因为要提交数据,所以要设置ContentType,json设置为application/x-www-form-urlencoded。
#region post请求,token放在请求头,当接收的参数是string
public static bool _myPostJsonJson(string strURL, string token, string jsonParam)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
req.Method = "POST";
req.Headers["Authorization"] = "X-Token=" + token; //token放入请求头中 token用于单点登录,无此要求可省略
req.ContentType = "application/json;charset=UTF-8"; //要提交数据,所以要设置ContentType,json设置为application/json;charset=UTF-8
#region 添加Post 参数
byte[] data = Encoding.UTF8.GetBytes(jsonParam);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
if (resp.StatusCode == HttpStatusCode.OK)
return true;
return false;
}
public static Task<bool> _myPostJsonJsonAsync(string strURL, string token, string jsonParam)
{
var task = new Task<bool>(() => _myPostJsonJson(strURL, token, jsonParam)); //参数为委托
task.Start();
return task;
}
#endregion
附:关于HttpWebRequest.ContentType详解
获取或设置请求的 Content-type HTTP 标头的值。默认值为null,且看它的其他值:
/// <summary>
/// HTTP 内容类型(Content-Type)
/// </summary>
public class HttpContentType
{
/// <summary>
/// 资源类型:普通文本
/// </summary>
public const string TEXT_PLAIN = "text/plain";
/// <summary>
/// 资源类型:JSON字符串
/// </summary>
public const string APPLICATION_JSON = "application/json";
/// <summary>
/// 资源类型:未知类型(数据流)
/// </summary>
public const string APPLICATION_OCTET_STREAM = "application/octet-stream";
/// <summary>
/// 资源类型:表单数据(键值对)
/// </summary>
public const string WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
/// <summary>
/// 资源类型:表单数据(键值对)。编码方式为 gb2312
/// </summary>
public const string WWW_FORM_URLENCODED_GB2312 = "application/x-www-form-urlencoded;charset=gb2312";
/// <summary>
/// 资源类型:表单数据(键值对)。编码方式为 utf-8
/// </summary>
public const string WWW_FORM_URLENCODED_UTF8 = "application/x-www-form-urlencoded;charset=utf-8";
/// <summary>
/// 资源类型:多分部数据
/// </summary>
public const string MULTIPART_FORM_DATA = "multipart/form-data";
}
提交的时候可以附加编码的方式(如req.ContentType = “application/json;charset=UTF-8”;),用来使对方服务器能够正确的解析。
该ContentType的属性包含请求的媒体类型。分配给ContentType属性的值在请求发送Content-typeHTTP标头时替换任何现有内容。
要清除Content-typeHTTP标头,可以将ContentType属性设置为null。
三、文件上传与文件下载
3.1 文件上传
3.1.1 文件上传代码架构
3.1.2 WebClient上传客户端文件至服务器
/// <summary>
/// WebClient上传文件至服务器
/// site http://www.jbxue.com
/// </summary>
/// <param name="localFilePath">文件名,全路径格式</param>
/// <param name="serverFolder">服务器文件夹路径</param>
/// <param name="reName">是否需要修改文件名,这里默认是日期格式</param>
/// <returns></returns>
public static bool UploadFile(string localFilePath, string serverFolder,bool reName)
{
string fileNameExt, newFileName, uriString;
if (reName)
{
fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1);
newFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileNameExt;
}
else
{
newFileName = localFilePath.Substring(localFilePath.LastIndexOf("\\")+1);
}
if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith("\\"))
{
serverFolder = serverFolder + "/";
}
uriString = serverFolder + newFileName; //服务器保存路径
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",localFilePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
else
{
MessageBox.Show("文件目前不可写!");
}
postStream.Close();
}
catch
{
//MessageBox.Show("文件上传失败,请稍候重试~");
return false;
}
return true;
}
3.1.3 服务端——文件上传
/// <summary>
/// 服务端需要的接口
/// </summary>
public interface IUploadServices
{
/// <summary>
/// 文件名(不含路径格式)
/// </summary>
string FileName { get; }
/// <summary>
/// 上载
/// </summary>
/// <param name="buffer"></param>
/// <param name="isEnd"></param>
void Upload(byte[] buffer, bool isEnd);
}
/// <summary>
/// 服务器端方法
/// </summary>
public class UploadServices : IUploadServices, IDisposable
{
private FileStream FSServer = null;
private static BinaryWriter BWServer = null;
private string _FileName = string.Empty;
/// <summary>
/// 待上传的文件名,不包含路径
/// </summary>
public string FileName
{
get { return this._FileName; }
set { this._FileName = value; }
}
/// <summary>
/// 上传文件保存路径,完全路径格式
/// </summary>
private string ServerPath
{
get
{
return Path.Combine("D:\\Test\\ProgressUpload", FileName);
}
}
public UploadServices()
{
}
public UploadServices(string fileName)
{
this._FileName = fileName;
/// 初始化对象
CreateFileStream();
}
/// <summary>
/// 创建对象
/// </summary>
/// <returns></returns>
private bool CreateFileStream()
{
try
{
FSServer = new FileStream(ServerPath, FileMode.Create, FileAccess.Write);
BWServer = new BinaryWriter(FSServer);
return true;
}
catch { return false; }
}
/// <summary>
/// 每次读取固定字节写入文件
/// </summary>
/// <param name="buffer"></param>
/// <param name="isEnd"></param>
public void Upload(byte[] buffer, bool isEnd)
{
BWServer.Write(buffer);
BWServer.Flush();
}
/// <summary>
/// 关闭对象
/// </summary>
private void CloseFileStream()
{
if (BWServer != null)
{
BWServer.Close();
BWServer = null;
}
if (FSServer != null)
{
FSServer.Close();
FSServer = null;
}
}
#region IDisposable 成员
/// <summary>
/// 销毁对象
/// </summary>
public void Dispose()
{
CloseFileStream();
}
#endregion
}
3.1.4 客户端——文件上传
/// <summary>
/// 客户端方法
/// </summary>
public class UploadCommon : IDisposable
{
public delegate void UploadHander(object sender);
/// <summary>
/// 上传前方法,参数为文件总大小
/// </summary>
public static event UploadHander BeforeUpLoad;
/// <summary>
/// 上传过程中方法,参数为当次上传文件大小
/// </summary>
public static event UploadHander DoUpLoad;
/// <summary>
/// 上传完成方法,参数为当次上传文件大小
/// </summary>
public static event UploadHander AfterUpLoad;
/// <summary>
/// 上传出错方法,参数为错误信息
/// </summary>
public static event UploadHander ErrorUpLoad;
private FileStream fs = null;
private BinaryReader br = null;
private int _UploadSize = 1024;
/// <summary>
/// 每次上载的文件数据大小(单位:字节),默认 1024 字节
/// </summary>
public int UploadSize
{
get { return this._UploadSize; }
set { this._UploadSize = value; }
}
/// <summary>
/// 通过字节流上传,使用委托控制进度条
/// </summary>
/// <param name="localFile">本地路径</param>
public void UpLoadFile(string localFile)
{
// 服务器端上传服务
UploadServices upload = new UploadServices(Path.GetFileName(localFile));
try
{
fs = new FileStream(localFile, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
// 上传前调用方法
if (BeforeUpLoad != null)
{
BeforeUpLoad(fs.Length);
}
while (true)
{
Byte[] buffer = br.ReadBytes(UploadSize);
if (buffer.Length < UploadSize)
{
upload.Upload(buffer, true);
// 上传完毕使用方法
if (AfterUpLoad != null)
{
AfterUpLoad(UploadSize);
}
break;
}
else
{
upload.Upload(buffer, false);
if (DoUpLoad != null)
{
DoUpLoad(UploadSize);
}
}
}
}
catch (Exception ex)
{
if (ErrorUpLoad != null)
{
ErrorUpLoad(ex.Message);
}
}
finally
{
Dispose();
upload.Dispose();
}
}
/// <summary>
/// 销毁对象
/// </summary>
private void CloseFileStream()
{
if (br != null)
{
br.Close();
}
if (fs != null)
{
fs.Close();
}
BeforeUpLoad = null;
DoUpLoad = null;
AfterUpLoad = null;
ErrorUpLoad = null;
}
#region IDisposable 成员
/// <summary>
/// 释放对象
/// </summary>
public void Dispose()
{
CloseFileStream();
}
#endregion
}
3.2 文件下载
3.2.1 文件下载代码架构
3.2.2 WebClient下载服务器文件至客户端
/// <summary>
/// 下载服务器文件至客户端
/// </summary>
class Helper_Download
{
/// <summary>
/// 下载服务器文件至客户端
/// </summary>
/// <param name="uri">被下载的文件地址</param>
/// <param name="savePath">另存放的目录</param>
public static bool Download(string uri, string savePath)
{
string fileName; //被下载的文件名
if (uri.IndexOf("\\") > -1)
{
fileName = uri.Substring(uri.LastIndexOf("\\") + 1);
}
else
{
fileName = uri.Substring(uri.LastIndexOf("/") + 1);
}
if (!savePath.EndsWith("/") && !savePath.EndsWith("\\"))
{
savePath = savePath + "/";
}
savePath += fileName; //另存为的绝对路径+文件名
WebClient client = new WebClient();
try
{
client.DownloadFile(uri, savePath);
}
catch
{
return false;
}
return true;
}
}
3.2.3 服务端——文件下载
/// <summary>
/// 服务端需要的接口
/// </summary>
public interface IDownloadServices
{
/// <summary>
/// 每次下载的大小
/// </summary>
int DownloadSize { get; set; }
/// <summary>
/// 待下载的文件名,完全路径格式
/// </summary>
string FullFileName { get; set; }
/// <summary>
/// 文件总大小
/// </summary>
long FileSize { get; }
/// <summary>
/// 获取文件的数据流对象
/// </summary>
/// <returns></returns>
byte[] GetBuffer();
}
/// <summary>
/// 服务器端方法
/// </summary>
public class DownloadServices : IDownloadServices, IDisposable
{
/// <summary>
/// 每次下载大小
/// </summary>
private const int PROGRESS_UNIT_SIZE = 1024;
private FileStream FSServer = null;
private BinaryReader BRServer = null;
/// <summary>
/// 构造函数中初始化对象
/// </summary>
public DownloadServices(string fullFileName)
{
this._FullFileName = fullFileName;
// 初始化创建对象
CreateFileStream();
}
/// <summary>
/// 创建对象
/// </summary>
/// <returns></returns>
private bool CreateFileStream()
{
try
{
FSServer = new FileStream(FullFileName, FileMode.Open, FileAccess.Read);
BRServer = new BinaryReader(FSServer);
_FileSize = FSServer.Length;
return true;
}
catch { return false; }
}
/// <summary>
/// 销毁对象
/// </summary>
private void CloseFileStream()
{
if (FSServer != null)
{
FSServer.Close();
}
if (BRServer != null)
{
BRServer.Close();
}
}
#region IDownloadServices 成员
private string _FullFileName = string.Empty;
/// <summary>
/// 文件名
/// </summary>
public string FullFileName
{
get
{
return this._FullFileName;
}
set
{
this._FullFileName = value;
}
}
private long _FileSize;
/// <summary>
/// 文件总大小
/// </summary>
public long FileSize
{
get
{
return _FileSize;
}
}
private int _DownloadSize = 1024;
/// <summary>
/// 每次下载的大小
/// </summary>
public int DownloadSize
{
get
{
return this._DownloadSize;
}
set
{
this._DownloadSize = value;
}
}
/// <summary>
/// 获取文件流数据
/// </summary>
/// <returns></returns>
public byte[] GetBuffer()
{
Byte[] buffer = BRServer.ReadBytes(PROGRESS_UNIT_SIZE);
return buffer;
}
#endregion
#region IDisposable 成员
/// <summary>
/// 销毁对象
/// </summary>
public void Dispose()
{
CloseFileStream();
}
#endregion
}
3.2.4 客户端——文件下载
/// <summary>
/// 客户端方法
/// </summary>
public class DownloadCommon : IDisposable
{
public delegate void DownloadHandler(object sender);
/// <summary>
/// 上传前方法,参数为文件总大小
/// </summary>
public static event DownloadHandler BeforeDownload;
/// <summary>
/// 上传过程中方法,参数为当次上传文件大小
/// </summary>
public static event DownloadHandler DoDownload;
/// <summary>
/// 上传完成方法,参数为当次上传文件大小
/// </summary>
public static event DownloadHandler AfterDownload;
/// <summary>
/// 上传出错方法,参数为错误信息
/// </summary>
public static event DownloadHandler ErrorDownload;
private FileStream fs = null;
private BinaryWriter bw = null;
private int _DownSize = 1024;
/// <summary>
/// 每次下载的数据大小(单位:字节),默认 1024 字节
/// </summary>
public int DownSize
{
get { return this._DownSize; }
set { this._DownSize = value; }
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="localFile">本地文件保存路径(完全路径格式)</param>
/// <param name="fullFileName">服务器文件路径(完全路径格式)</param>
public void Download(string localFile, string fullFileName)
{
DownloadServices down = new DownloadServices(fullFileName) { DownloadSize = DownSize };
// 待下载的总文件大小
long fileSize = down.FileSize;
try
{
// 读取本地文件到流对象中
fs = new FileStream(localFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
bw = new BinaryWriter(fs);
// 上传前调用方法
if (BeforeDownload != null)
{
BeforeDownload(fileSize);
}
Byte[] buffer;
while ((buffer = down.GetBuffer()).Length > 0)
{
bw.Write(buffer);
bw.Flush();
// 下载过程中
if (DoDownload != null)
{
DoDownload(buffer.Length);
}
}
// 下载完毕
if (AfterDownload != null)
{
AfterDownload(null);
}
}
catch (Exception ex)
{
if (ErrorDownload != null)
{
ErrorDownload(ex.Message);
}
}
finally
{
down.Dispose();
Dispose();
}
}
/// <summary>
/// 销毁对象
/// </summary>
private void CloseFileStream()
{
if (bw != null)
{
bw.Close();
}
if (fs != null)
{
fs.Close();
}
BeforeDownload = null;
DoDownload = null;
AfterDownload = null;
ErrorDownload = null;
}
#region IDisposable 成员
/// <summary>
/// 释放对象
/// </summary>
public void Dispose()
{
CloseFileStream();
}
#endregion
}
四、小结
本文介绍C#网络请求,包括Get请求、Post请求、文件上传、文件下载。
天天打码,天天进步!
源工程文件:https://download.csdn.net/download/qq_36963950/12250934
转载:https://blog.csdn.net/qq_36963950/article/details/104883845