C#开发WinForm之Http请求

秒速五厘米 2022-04-11 03:16 1679阅读 0赞

C#开发WinForm之Http请求

文章目录

    • C#开发WinForm之Http请求
  • 前言
  • http请求工具库里
  • 使用方法
    • Get请求
    • Post请求
  • 扩展
    • 文件上传
    • 文件下载

前言

HTTP请求是常见的web开发请求,简历也容易上手,当然对于 前端来说,jsweb的http很熟悉,而换种语言的c#是怎样的呢?

Newtonsoft.Json是一个处理json格式的c#库,我们可以去下载它并学习使用它。

http请求工具库里

我的工具库里使用了HttpClient。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.Net.Security;
  8. using System.IO;
  9. using System.Net.Http;
  10. using System.Net.Http.Headers;
  11. using System.Xml.Serialization;
  12. using DongliCAD.utils;
  13. using Newtonsoft.Json;
  14. using Newtonsoft.Json.Linq;
  15. using System.Windows.Forms;
  16. using System.Text.RegularExpressions;
  17. using Bricscad.ApplicationServices;
  18. using Bricscad.EditorInput;
  19. using DongliCAD.common;
  20. namespace DongliCAD.utils
  21. {
  22. class HttpUtil
  23. {
  24. /// <summary>
  25. /// get请求
  26. /// </summary>
  27. /// <param name="url"></param>
  28. /// <returns></returns>
  29. public static JObject GetResponse(string url)
  30. {
  31. try
  32. {
  33. if (string.IsNullOrEmpty(url))
  34. {
  35. throw new ArgumentNullException("url");
  36. }
  37. if (url.StartsWith("https"))
  38. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  39. HttpClient httpClient = new HttpClient();
  40. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  41. if (GlobalData.Authorization.Length > 0)
  42. {
  43. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  44. }
  45. HttpResponseMessage response = httpClient.GetAsync(url).Result;
  46. StatusCodeHandler(response);
  47. if (response.IsSuccessStatusCode)
  48. {
  49. string result = response.Content.ReadAsStringAsync().Result;
  50. JObject jo = (JObject)JsonConvert.DeserializeObject(result);
  51. return jo;
  52. }
  53. }
  54. catch(Exception e)
  55. {
  56. string msg = e.InnerException.InnerException.Message;
  57. if(msg == "无法连接到远程服务器")
  58. {
  59. AlertUtil.Show("服务器无响应,请重新配置环境");
  60. exceptionHandler("连接失败");
  61. }
  62. }
  63. return new JObject();
  64. }
  65. public static T GetResponse<T>(string url)
  66. where T : class, new()
  67. {
  68. T result = default(T);
  69. if (string.IsNullOrEmpty(url))
  70. {
  71. throw new ArgumentNullException("url");
  72. }
  73. if (url.StartsWith("https"))
  74. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  75. HttpClient httpClient = new HttpClient();
  76. httpClient.DefaultRequestHeaders.Accept.Add(
  77. new MediaTypeWithQualityHeaderValue("application/json"));
  78. if (GlobalData.Authorization.Length > 0)
  79. {
  80. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  81. }
  82. try {
  83. HttpResponseMessage response = httpClient.GetAsync(url).Result;
  84. StatusCodeHandler(response);
  85. if (response.IsSuccessStatusCode)
  86. {
  87. Task<string> t = response.Content.ReadAsStringAsync();
  88. string s = t.Result;
  89. result = JsonConvert.DeserializeObject<T>(s);
  90. }
  91. }
  92. catch(Exception e)
  93. {
  94. string msg = e.InnerException.InnerException.Message;
  95. if(msg == "无法连接到远程服务器")
  96. {
  97. AlertUtil.Show("服务器无响应,请重新配置环境");
  98. exceptionHandler("连接失败");
  99. }
  100. }
  101. return result;
  102. }
  103. /// <summary>
  104. /// post请求
  105. /// </summary>
  106. /// <param name="url"></param>
  107. /// <param name="postData">post数据</param>
  108. /// <returns></returns>
  109. public static JObject PostResponse(string url, string postData)
  110. {
  111. if (string.IsNullOrEmpty(url))
  112. {
  113. throw new ArgumentNullException("url");
  114. }
  115. if (url.StartsWith("https"))
  116. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  117. HttpContent httpContent = new StringContent(postData);
  118. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  119. HttpClient httpClient = new HttpClient();
  120. if (GlobalData.Authorization.Length > 0)
  121. {
  122. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  123. }
  124. try {
  125. HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
  126. StatusCodeHandler(response);
  127. AuthorizationHandler(response, url);
  128. if (response.IsSuccessStatusCode)
  129. {
  130. string result = response.Content.ReadAsStringAsync().Result;
  131. JObject jo = (JObject)JsonConvert.DeserializeObject(result);
  132. return jo;
  133. }
  134. }
  135. catch (Exception e)
  136. {
  137. string msg = e.InnerException.InnerException.Message;
  138. if (msg == "无法连接到远程服务器")
  139. {
  140. AlertUtil.Show("服务器无响应,请重新配置环境");
  141. exceptionHandler("连接失败");
  142. }
  143. }
  144. return new JObject();
  145. }
  146. private static Boolean StatusCodeHandler(HttpResponseMessage response)
  147. {
  148. Boolean ct = true;
  149. String statusCode = response.StatusCode.ToString();
  150. string result = response.Content.ReadAsStringAsync().Result;
  151. JObject jo = (JObject)JsonConvert.DeserializeObject(result);
  152. if (statusCode == HttpStatusCode.Unauthorized.ToString())
  153. {
  154. AlertUtil.Show("请重新登陆");
  155. LoginForm login = new LoginForm();
  156. login.ShowDialog();
  157. } else if (statusCode == HttpStatusCode.Forbidden.ToString())
  158. {
  159. AlertUtil.Show("禁止访问" + jo["data"]["msg"]);
  160. }
  161. else if (statusCode == HttpStatusCode.NotFound.ToString())
  162. {
  163. AlertUtil.Show("请求失败");
  164. }else if(statusCode == HttpStatusCode.BadRequest.ToString())
  165. {
  166. AlertUtil.Show("400");
  167. }
  168. return ct;
  169. }
  170. private static void AuthorizationHandler(HttpResponseMessage response, string url)
  171. {
  172. Regex reg = new Regex("(.+)/login$");
  173. Boolean isLogin = reg.IsMatch(url);
  174. if (isLogin)
  175. {
  176. GlobalData.Authorization = getHeaderByKey(response, "Authorization");
  177. }
  178. }
  179. private static string getHeaderByKey(HttpResponseMessage response, string key)
  180. {
  181. string result = "";
  182. string header = response.Headers.ToString();
  183. string[] headers = header.Split("\r\n".ToCharArray());
  184. if(headers.Count() > 0)
  185. {
  186. foreach (string item in headers)
  187. {
  188. Regex reg = new Regex("^" + key + ":(.+)");
  189. if (reg.IsMatch(item))
  190. {
  191. string[] tokens = item.Split(':');
  192. if (tokens[0].ToString() == key)
  193. {
  194. result = tokens[1].ToString();
  195. break;
  196. }
  197. }
  198. else
  199. {
  200. reg = new Regex("^" + key + "=(.+)");
  201. if (reg.IsMatch(item))
  202. {
  203. string[] tokens = item.Split('=');
  204. if (tokens[0].ToString() == key)
  205. {
  206. result = tokens[1].ToString();
  207. break;
  208. }
  209. }
  210. }
  211. }
  212. }
  213. return result;
  214. }
  215. /// <summary>
  216. /// 发起post请求
  217. /// </summary>
  218. /// <typeparam name="T"></typeparam>
  219. /// <param name="url">url</param>
  220. /// <param name="postData">post数据</param>
  221. /// <returns></returns>
  222. public static T PostResponse<T>(string url, string postData)
  223. where T : class, new()
  224. {
  225. if (string.IsNullOrEmpty(url))
  226. {
  227. throw new ArgumentNullException("url");
  228. }
  229. if (url.StartsWith("https"))
  230. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  231. HttpContent httpContent = new StringContent(postData);
  232. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  233. HttpClient httpClient = new HttpClient();
  234. T result = default(T);
  235. if (GlobalData.Authorization.Length > 0)
  236. {
  237. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  238. }
  239. try
  240. {
  241. HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
  242. StatusCodeHandler(response);
  243. if (response.IsSuccessStatusCode)
  244. {
  245. Task<string> t = response.Content.ReadAsStringAsync();
  246. string s = t.Result;
  247. result = JsonConvert.DeserializeObject<T>(s);
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. string msg = e.InnerException.InnerException.Message;
  253. if (msg == "无法连接到远程服务器")
  254. {
  255. AlertUtil.Show("服务器无响应,请重新配置环境");
  256. exceptionHandler("连接失败");
  257. }
  258. }
  259. return result;
  260. }
  261. /// <summary>
  262. /// put请求
  263. /// </summary>
  264. /// <param name="url"></param>
  265. /// <param name="putData">put数据</param>
  266. /// <returns></returns>
  267. public static JObject PutResponse(string url, string putData = "")
  268. {
  269. if (string.IsNullOrEmpty(url))
  270. {
  271. throw new ArgumentNullException("url");
  272. }
  273. if (url.StartsWith("https"))
  274. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  275. HttpContent httpContent = new StringContent(putData);
  276. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  277. HttpClient httpClient = new HttpClient();
  278. if (GlobalData.Authorization.Length > 0)
  279. {
  280. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  281. }
  282. try
  283. {
  284. HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
  285. StatusCodeHandler(response);
  286. if (response.IsSuccessStatusCode)
  287. {
  288. string result = response.Content.ReadAsStringAsync().Result;
  289. JObject jo = (JObject)JsonConvert.DeserializeObject(result);
  290. return jo;
  291. }
  292. }
  293. catch (Exception e)
  294. {
  295. string msg = e.InnerException.InnerException.Message;
  296. if (msg == "无法连接到远程服务器")
  297. {
  298. AlertUtil.Show("服务器无响应,请重新配置环境");
  299. exceptionHandler("连接失败");
  300. }
  301. }
  302. return new JObject();
  303. }
  304. /// <summary>
  305. /// delete请求
  306. /// </summary>
  307. /// <param name="url"></param>
  308. /// <returns></returns>
  309. public static JObject DeleteResponse(string url)
  310. {
  311. if (string.IsNullOrEmpty(url))
  312. {
  313. throw new ArgumentNullException("url");
  314. }
  315. if (url.StartsWith("https"))
  316. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  317. HttpClient httpClient = new HttpClient();
  318. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  319. if (GlobalData.Authorization.Length > 0)
  320. {
  321. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  322. }
  323. try
  324. {
  325. HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
  326. StatusCodeHandler(response);
  327. string statusCode = response.StatusCode.ToString();
  328. if (response.IsSuccessStatusCode)
  329. {
  330. string result = response.Content.ReadAsStringAsync().Result;
  331. JObject jo = (JObject)JsonConvert.DeserializeObject(result);
  332. return jo;
  333. }
  334. }
  335. catch (Exception e)
  336. {
  337. string msg = e.InnerException.InnerException.Message;
  338. if (msg == "无法连接到远程服务器")
  339. {
  340. AlertUtil.Show("服务器无响应,请重新配置环境");
  341. exceptionHandler("连接失败");
  342. }
  343. }
  344. return new JObject();
  345. }
  346. private static void exceptionHandler(string msg)
  347. {
  348. throw new DyConnectException(msg);
  349. }
  350. }
  351. }

其中

  1. if (GlobalData.Authorization.Length > 0)
  2. {
  3. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  4. }

是我登陆成功后返回的token,我把token放在header放在头部传给后台,如果具体业务不一样,可以修改。
使用try…catch当连接后台不成功时抛出异常。
DyConnectException是我自定义的一个异常类,用于处理连接后台不成功时的异常。
DyConnectException.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace DongliCAD
  7. {
  8. class DyConnectException : Exception
  9. {
  10. public int status = 911;
  11. public string message;
  12. public DyConnectException(string message)
  13. {
  14. this.message = message;
  15. }
  16. }
  17. }

其中Get和Post我提供了2种方式请求,一个是返回json格式的字段串,一个是解析成对象。

使用方法

Get请求

  1. 返回json格式字符串,这个字符串解析成JObject对象,(JObject是Newtonsoft.Json里对象)

    JObject jObject = HttpUtil.GetResponse(“请求的url地址”);

取数据方式:jObject["code"].ToString()jObject["code"]["code1"].ToString()

  1. 返回对象

    ItemTypeRootVo itemTypeRootVo = HttpUtil.GetResponse(“请求的url地址”);

ItemTypeRootVo是我自定义的对象,比如如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace DongliCAD.vo
  7. {
  8. public class ItemTypeRootVo
  9. {
  10. /// <summary>
  11. ///
  12. /// </summary>
  13. public int code { get; set; }
  14. /// <summary>
  15. ///
  16. /// </summary>
  17. public string msg { get; set; }
  18. /// <summary>
  19. ///
  20. /// </summary>
  21. public int error { get; set; }
  22. /// <summary>
  23. ///
  24. /// </summary>
  25. public List<ItemTypeVo> data { get; set; }
  26. }
  27. public class ItemTypeVo
  28. {
  29. /// <summary>
  30. ///
  31. /// </summary>
  32. public string uid { get; set; }
  33. /// <summary>
  34. /// 总装图
  35. /// </summary>
  36. public string itemTypeName { get; set; }
  37. /// <summary>
  38. /// 类型
  39. /// </summary>
  40. public string userTitle1 { get; set; }
  41. /// <summary>
  42. /// 中心高
  43. /// </summary>
  44. public string userTitle2 { get; set; }
  45. /// <summary>
  46. /// 总中心距
  47. /// </summary>
  48. public string userTitle3 { get; set; }
  49. /// <summary>
  50. /// 级数
  51. /// </summary>
  52. public string userTitle4 { get; set; }
  53. /// <summary>
  54. /// 输入轴轴径
  55. /// </summary>
  56. public string userTitle5 { get; set; }
  57. /// <summary>
  58. /// 输出轴轴径
  59. /// </summary>
  60. public string userTitle6 { get; set; }
  61. /// <summary>
  62. /// 输出力矩
  63. /// </summary>
  64. public string userTitle7 { get; set; }
  65. /// <summary>
  66. ///
  67. /// </summary>
  68. public string userTitle8 { get; set; }
  69. /// <summary>
  70. ///
  71. /// </summary>
  72. public int order { get; set; }
  73. }
  74. }

那么在请求成功后,会自动把json数据解析成ItemTypeRootVo对象,相对来说更方便些。

Post请求

  1. 返回字符串请求,这种请求的get类似,同时post需要向后台传递数据。使用JObject或JArray。
    比如传递对象

    JObject jObj = new JObject();

    1. jObj.Add(new JProperty("userId", userName));
    2. jObj.Add(new JProperty("password", password));
    3. JObject result = HttpUtil.PostResponse("请求的url地址", jObj.ToString());

或者传递数组

  1. JObject jObj = new JObject();
  2. JArray jArray = new JArray();
  3. jObj.Add(new JProperty("uid", workspaceCadInfoVo.itemRevUid));
  4. jObj.Add(new JProperty("ctype", "ITEMREVISION"));
  5. jArray.Add(jObj);
  6. JObject result = HttpUtil.PostResponse("请求的url地址", jArray.ToString());
  1. 返回对象,同get一样。

扩展

文件上传

有时候我们需要上传文件,同时也上传数据。方法如下,以异步方式上传

  1. /// <summary>
  2. /// post请求
  3. /// </summary>
  4. /// <param name="url"></param>
  5. /// <param name="postData">post数据</param>
  6. /// <returns></returns>
  7. public static JObject PostFileResponse(string url, MultipartFormDataContent postData)
  8. {
  9. if (string.IsNullOrEmpty(url))
  10. {
  11. throw new ArgumentNullException("url");
  12. }
  13. if (url.StartsWith("https"))
  14. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  15. //HttpContent httpContent = new FormCo StringContent(postData);
  16. //postData.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  17. HttpClient httpClient = new HttpClient();
  18. if (GlobalData.Authorization.Length > 0)
  19. {
  20. httpClient.DefaultRequestHeaders.Add("Authorization", GlobalData.Authorization);
  21. }
  22. try
  23. {
  24. HttpResponseMessage response = httpClient.PostAsync(url, postData).Result;
  25. StatusCodeHandler(response);
  26. AuthorizationHandler(response, url);
  27. if (response.IsSuccessStatusCode)
  28. {
  29. string result = response.Content.ReadAsStringAsync().Result;
  30. JObject jo = (JObject)JsonConvert.DeserializeObject(result);
  31. return jo;
  32. }
  33. }
  34. catch (Exception e)
  35. {
  36. string msg = e.InnerException.InnerException.Message;
  37. if (msg == "无法连接到远程服务器")
  38. {
  39. AlertUtil.Show("服务器无响应,请重新配置环境");
  40. exceptionHandler("连接失败");
  41. }
  42. }
  43. return new JObject();
  44. }

使用方式

  1. MultipartFormDataContent dataContent = new MultipartFormDataContent();
  2. //传文件
  3. string pdfFileName = "test.pdf";
  4. FileStream pdfFsRead = new FileStream("D:/test/" + pdfFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  5. byte[] pdfBytes = new byte[(int)pdfFsRead.Length];
  6. pdfFsRead.Read(pdfBytes, 0, pdfBytes.Length);
  7. //ByteArrayContent pdfArrayContent = new ByteArrayContent(File.ReadAllBytes("D:/test/" + pdfFileName));
  8. ByteArrayContent pdfArrayContent = new ByteArrayContent(pdfBytes);
  9. pdfArrayContent.Headers.Add("Content-Type", "multipart/form-data");
  10. dataContent.Add(pdfArrayContent, "files", pdfFileName);
  11. //传数据,注意格式是value-key,不是key-value
  12. dataContent.Add(new StringContent("123"), "itemRevisionUid");
  13. dataContent.Add("456", "datasetUid");
  14. //请求接口
  15. JObject jObject = HttpUtil.PostFileResponse("请求的url地址", dataContent);

上面将文件和数据都放到MultipartFormDataContent对象里.
后台接口类似如下(使用kotlin语法写的。和java差不多)

  1. /**
  2. * 保存图纸和pdf文档
  3. */
  4. @PostMapping("/saveDrawingno")
  5. fun saveDrawingno(
  6. @RequestParam itemRevisionUid:Long,@RequestParam datasetUid: Long,
  7. @RequestParam files: Array<MultipartFile>): ResponseEntity<Any> {
  8. //逻辑部分
  9. }

实现了即上传文件又上传数据的功能。

文件下载

文件下载包括同步下载和异常下载。
工具类HttpDownUtil.cs如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.Net.Security;
  8. using System.IO;
  9. using System.Net.Http;
  10. using System.Net.Http.Headers;
  11. using System.Xml.Serialization;
  12. using DongliCAD.utils;
  13. using Newtonsoft.Json;
  14. using Newtonsoft.Json.Linq;
  15. using System.Windows.Forms;
  16. using System.Text.RegularExpressions;
  17. using System.Collections.Specialized;
  18. namespace DongliCAD.utils
  19. {
  20. class HttpDownUtil
  21. {
  22. /**********************************************上传***************************************************************************/
  23. public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
  24. {
  25. var property = typeof(WebHeaderCollection).GetProperty("InnerCollection",
  26. System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  27. if (property != null)
  28. {
  29. var collection = property.GetValue(header, null) as NameValueCollection;
  30. collection[name] = value;
  31. }
  32. }
  33. /**********************************************下载***************************************************************************/
  34. /********************同步下载***************************/
  35. /// <summary>
  36. /// 同步下载
  37. /// Http下载文件
  38. /// </summary>
  39. public static string HttpDownloadFile(string url, string path)
  40. {
  41. // 设置参数
  42. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  43. if (GlobalData.Authorization.Length > 0)
  44. {
  45. request.Headers.Add("Authorization", GlobalData.Authorization);
  46. }
  47. //发送请求并获取相应回应数据
  48. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  49. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  50. Stream responseStream = response.GetResponseStream();
  51. //创建本地文件写入流
  52. Stream stream = new FileStream(path, FileMode.Create);
  53. byte[] bArr = new byte[1024];
  54. int size = responseStream.Read(bArr, 0, (int)bArr.Length);
  55. while (size > 0)
  56. {
  57. stream.Write(bArr, 0, size);
  58. size = responseStream.Read(bArr, 0, (int)bArr.Length);
  59. }
  60. stream.Close();
  61. responseStream.Close();
  62. return path;
  63. }
  64. /********************异步下载***************************/
  65. /// <summary>
  66. /// 异步回调
  67. /// </summary>
  68. /// <param name="result">Result.</param>
  69. private static void BeginResponseCallback(IAsyncResult result)
  70. {
  71. DownloadTmp downloadInfo = (DownloadTmp)result.AsyncState;
  72. HttpWebRequest Request = downloadInfo.webRequest;
  73. HttpWebResponse Response = (HttpWebResponse)Request.EndGetResponse(result);
  74. if (Response.StatusCode == HttpStatusCode.OK || Response.StatusCode == HttpStatusCode.Created)
  75. {
  76. string filePath = downloadInfo.filePath;
  77. if (File.Exists(filePath))
  78. {
  79. File.Delete(filePath);
  80. }
  81. //FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
  82. FileStream fs = File.OpenWrite(filePath);
  83. Stream stream = Response.GetResponseStream();
  84. int count = 0;
  85. int num = 0;
  86. if (Response.ContentLength > 0)
  87. {
  88. downloadInfo.AllContentLength = Response.ContentLength;
  89. var buffer = new byte[2048 * 100];
  90. do
  91. {
  92. num++;
  93. count = stream.Read(buffer, 0, buffer.Length);
  94. downloadInfo.currentContentLength = num * buffer.Length;
  95. fs.Write(buffer, 0, count);
  96. if (downloadInfo.loadingCallback != null)
  97. {
  98. float pro = (float)fs.Length / Response.ContentLength * 100;
  99. downloadInfo.loadingCallback((int)pro);
  100. }
  101. } while (count > 0);
  102. }
  103. fs.Close();
  104. Response.Close();
  105. if (downloadInfo.succeedCallback != null)
  106. {
  107. downloadInfo.succeedCallback();
  108. }
  109. }
  110. else
  111. {
  112. Response.Close();
  113. if (downloadInfo.failedCallback != null)
  114. {
  115. downloadInfo.failedCallback();
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// 下载文件,异步
  121. /// </summary>
  122. /// <param name="URL">下载路径</param>
  123. /// <param name="downloadPath">文件下载路径</param>
  124. /// <returns></returns>
  125. public static void HttpDownloadFileAsyn(string URL, ref DownloadTmp downloadInfo)
  126. {
  127. HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
  128. downloadInfo.webRequest = Request;
  129. Request.BeginGetResponse(BeginResponseCallback, downloadInfo);
  130. }
  131. }
  132. /// <summary>
  133. /// 下载请求信息
  134. /// </summary>
  135. public class DownloadTmp
  136. {
  137. /// <summary>
  138. /// 文件名
  139. /// </summary>
  140. public string fileName;
  141. /// <summary>
  142. /// 下载路径
  143. /// </summary>
  144. public string filePath;
  145. /// <summary>
  146. /// 下载进度回调
  147. /// </summary>
  148. public Action<int> loadingCallback;
  149. /// <summary>
  150. /// 完成回调
  151. /// </summary>
  152. public Action succeedCallback;
  153. /// <summary>
  154. /// 失败回调
  155. /// </summary>
  156. public Action failedCallback;
  157. /// <summary>
  158. /// webRequest
  159. /// </summary>
  160. public HttpWebRequest webRequest;
  161. public long AllContentLength;
  162. public long currentContentLength;
  163. }
  164. }

同步下载:HttpDownloadFile()
异步下载:HttpDownloadFileAsyn()

使用方式也很简单

  1. DownloadTmp downloadTmp = new DownloadTmp();
  2. downloadTmp.filePath = @“D:\test\666.txt”;
  3. HttpDownloadZip(downUrl, ref downloadTmp);

其中在外部我们也可以访问downloadTmp里的参数。谁让它用ref修饰呢

发表评论

表情:
评论列表 (有 0 条评论,1679人围观)

还没有评论,来说两句吧...

相关阅读