RestSharp库请在NuGet中搜索安装。本文使用的版本是105.0.0
Header参数实体(可以根据实际情况修改)
public class HeaderParams
{
private string _x_hw_id = string.Empty;
private string _x_hw_appkey = string.Empty;
private string _supplier = string.Empty;
private string _accept_language = string.Empty;
private bool _isBase64Account = false;
public string X_HW_ID
{
get { return _x_hw_id; }
set { _x_hw_id = value; }
}
public string X_HW_APPKEY
{
get { return _x_hw_appkey; }
set { _x_hw_appkey = value; }
}
public bool IsBase64Account
{
get { return _isBase64Account; }
set { _isBase64Account = value; }
}
public string Supplier
{
get {
string s = string.Empty;
if (!string.IsNullOrEmpty(_supplier))
{
if (_isBase64Account) { s = Convert.ToBase64String(Encoding.Unicode.GetBytes(_supplier)); }
else { s = _supplier; }
}
return s;
}
set { _supplier = value; }
}
public string Accept_Language
{
get { return _accept_language; }
set { _accept_language = value; }
}
}
普通文件下载100M以下,可以通过RestClient的Execute函数返回一个IRestResponse对象,该对象的RawBytes就是接口返回的字节流。
public byte[] Get(Models.HeaderParams _params, string _url)
{
var client = new RestClient(_url);
client.Timeout = 900000;
var request = new RestRequest(Method.GET);
request.AddHeader("X-HW-ID", _params.X_HW_ID);
request.AddHeader("X-HW-APPKEY", _params.X_HW_APPKEY);
IRestResponse response = client.Execute(request);
return response.RawBytes;
}
但是上述的方式在遇到大小超过60M的时候就会不稳定,超过100M时直接返回了null值。
所以比较推荐的做法是使用下面的方法来下载。
public byte[] GetBigFile(Models.HeaderParams _params, string _url) {
var client = new RestClient(_url);
client.Timeout = 900000;
var request = new RestRequest(Method.GET);
request.AddHeader("X-HW-ID", _params.X_HW_ID);
request.AddHeader("X-HW-APPKEY", _params.X_HW_APPKEY);
string tempFile = Path.GetTempFileName();
try
{
using (var writer = File.OpenWrite(tempFile))
{
request.ResponseWriter = responseStream =>
{
using (responseStream)
{
responseStream.CopyTo(writer);
}
};
var response = client.DownloadData(request);
}
FileStream fs = new FileStream(tempFile, FileMode.Open);
byte[] infbytes = new byte[(int)fs.Length];
fs.Read(infbytes, 0, infbytes.Length);
fs.Close();
File.Delete(tempFile);
return infbytes;
}
catch (Exception ex) {
return null;
}
}
上述的方法会在C盘用户文件夹的临时文件夹中创建一个tmp文件,来做接收。接收完成后就可以把这个文件用流的方式写入到指定的路径中。
下载完成后一定要把这个tmp文件给删除掉(即调用File.Delete()),否则会造成临时文件过多占用磁盘空间的问题。这种方式比起第一种多了一次IO请求,但是胜在稳定。目前测试100M~1G大小的文件都没有问题。