CNAS取数仪器端升级
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SendDataOperation.cs 2.6KB

4 maanden geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using CnasSynchronousCommon;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Text;
  8. using System.Web.Script.Serialization;
  9. namespace CnasSynchronusClient
  10. {
  11. /// <summary>
  12. /// 发送到API的相关操作类
  13. /// </summary>
  14. public class SendDataOperation
  15. {
  16. public string Url { get; set; }
  17. public string Route { get; set; }
  18. public string SendMethod { get; set; }
  19. public string RequestData { get; set; }
  20. public object SendContent{ get; set; }
  21. public bool IfSuccess { get; set; }
  22. public string ErrorMessage { get; set; }
  23. public void SendData()
  24. {
  25. try
  26. {
  27. string jsonData = new JavaScriptSerializer().Serialize(SendContent);
  28. byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
  29. //3.创建请求对象,并设置相关的属性;
  30. WebRequest webRequest = WebRequest.Create(Url + Route);
  31. webRequest.Method = SendMethod;
  32. webRequest.ContentType = "application/json";
  33. webRequest.ContentLength = byteArray.Length;
  34. //4.获取字节流对象,并向流中写入数据(请求对象和流对象关联)
  35. Stream byteStream = webRequest.GetRequestStream();
  36. byteStream.Write(byteArray, 0, byteArray.Length);
  37. byteStream.Close();
  38. //5.创建响应对象
  39. WebResponse webResponse = webRequest.GetResponse();
  40. //6.响应对应转换成http请求响应
  41. var httpWebResponse = (HttpWebResponse)webResponse;
  42. //7.如果请求成功,则读取所有数据
  43. if (httpWebResponse.StatusCode == HttpStatusCode.OK)
  44. {
  45. //7.1 获取返回的数据流
  46. byteStream = webResponse.GetResponseStream();
  47. //7.2 根据返回的数据流创建读取器
  48. StreamReader reader = new StreamReader(byteStream, Encoding.UTF8);
  49. //7.3 读取所有数据
  50. RequestData = reader.ReadToEnd();
  51. IfSuccess = true;
  52. }
  53. else
  54. {
  55. IfSuccess = false;
  56. ErrorMessage = "未能成功发送请求";
  57. }
  58. }
  59. catch (Exception ex)
  60. {
  61. IfSuccess = false;
  62. ErrorMessage = ex.Message;
  63. }
  64. }
  65. }
  66. }