当前位置:   article > 正文

C# HTTP请求

c# http请求

        一个http请求的工具类。这个就不必多说了,但是这里为了可以应对较多场景,加入了一个传入参数的类型,用来支持各种的数据,这里再提一下StringText这个枚举类型,访问.net core webapi的接口时,假如定义接收参数为[FromBody]String,那边必须再加引号转一下,否则获取不到,在Swagger上也一样,但是用Jquery的话,直接json.stringify()转一下是没问题的(我感觉这里是个深坑,当然你要用其他方式接收的话可以避免这个问题);同时返回结果有string和byte[]两种类型的数据。用来直接取结果集或者做文件的下载。

实现功能:

C#模拟HTTP请求,获取返回的数据

开发环境:

开发工具: Visual Studio 2019

.NET版本:.NET Core 3.1

实现代码:

  1. public class HttpUtil {
  2. public static HttpResult HttpRequest(HttpItem httpItem) {
  3. HttpResult result = new HttpResult();
  4. try {
  5. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(httpItem.Url);
  6. httpWebRequest.Method = httpItem.Method.ToString();
  7. httpWebRequest.ContentType = httpItem.ContentType;
  8. httpWebRequest.Headers = httpItem.Header;
  9. httpWebRequest.Timeout = httpItem.TimeOut;
  10. if(httpItem.Method == RequestMethod.POST && (httpItem.RequestValue != null)) {
  11. using(Stream requestStream = httpWebRequest.GetRequestStream()) {
  12. requestStream.Write(httpItem.RequestValue, 0, httpItem.RequestValue.Length);
  13. httpWebRequest.ContentLength = httpItem.RequestValue.Length;
  14. }
  15. }
  16. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  17. using(Stream responseStream = httpWebResponse.GetResponseStream()) {
  18. MemoryStream memoryStream = new MemoryStream();
  19. responseStream.CopyTo(memoryStream);
  20. result.HttpByteData = memoryStream.ToArray();
  21. memoryStream.Seek(0, SeekOrigin.Begin);
  22. result.HttpStringData = (httpWebResponse.ContentEncoding != null && httpWebResponse.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase)) ? memoryStream.ReadGzipText(httpItem.Encoding) : memoryStream.ReadText(httpItem.Encoding);
  23. }
  24. return result;
  25. }
  26. catch(Exception ex) {
  27. result.Status = false;
  28. result.Msg = ex.Message;
  29. return result;
  30. }
  31. }
  32. }
  33. public class HttpItem {
  34. /// <summary>
  35. /// Url地址
  36. /// </summary>
  37. private string url;
  38. public string Url
  39. {
  40. get
  41. {
  42. if(!url.ToLower().StartsWith("http")) {
  43. url = "http://" + url;
  44. }
  45. return url;
  46. }
  47. set { url = value; }
  48. }
  49. /// <summary>
  50. /// Method
  51. /// </summary>
  52. public RequestMethod Method { get; set; } = RequestMethod.POST;
  53. /// <summary>
  54. /// 超时时间
  55. /// </summary>
  56. public int TimeOut { get; set; } = 1000 * 60;
  57. /// <summary>
  58. /// 接收的ContentType
  59. /// </summary>
  60. public string ContentType { get; set; } = "application/json";
  61. /// <summary>
  62. /// 发送的ContentType
  63. /// </summary>
  64. public string HeaderContentType { get; set; } = "application/json";
  65. /// <summary>
  66. ///
  67. /// </summary>
  68. public string UserAgent { get; set; }
  69. /// <summary>
  70. /// 编码
  71. /// </summary>
  72. public Encoding Encoding { get; set; } = Encoding.UTF8;
  73. /// <summary>
  74. /// 发送的数据类型
  75. /// </summary>
  76. public RequesDataType RequestDataType { get; set; } = RequesDataType.Text;
  77. /// <summary>
  78. /// 发送的数据
  79. /// </summary>
  80. public object RequestData { get; set; }
  81. /// <summary>
  82. /// 根据数据类型转换数据
  83. /// </summary>
  84. public byte[] RequestValue
  85. {
  86. get
  87. {
  88. byte[] bytes = null;
  89. if(RequestData != null) {
  90. switch(RequestDataType) {
  91. case RequesDataType.Text:
  92. bytes = Encoding.GetBytes(RequestData.ToString());
  93. break;
  94. case RequesDataType.StringText:
  95. bytes = Encoding.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(RequestData));
  96. break;
  97. case RequesDataType.Byte:
  98. bytes = RequestData as byte[];
  99. break;
  100. }
  101. }
  102. return bytes;
  103. }
  104. }
  105. private WebHeaderCollection _header;
  106. /// <summary>
  107. /// 设置Header
  108. /// </summary>
  109. public WebHeaderCollection Header
  110. {
  111. get
  112. {
  113. if(_header == null) {
  114. _header = new WebHeaderCollection();
  115. }
  116. _header.Add(HttpResponseHeader.ContentType, HeaderContentType);
  117. return _header;
  118. }
  119. set { _header = value; }
  120. }
  121. public HttpItem(string url, RequesDataType requestDataType = RequesDataType.Text, object requestData = null) {
  122. Url = url;
  123. RequestDataType = requestDataType;
  124. RequestData = requestData;
  125. }
  126. }
  127. public class HttpResult {
  128. public bool Status { get; set; } = true;
  129. public string Msg { get; set; } = "Success";
  130. public string HttpStringData { get; set; }
  131. public byte[] HttpByteData { get; set; }
  132. }
  133. public enum RequestMethod {
  134. GET, POST
  135. }
  136. public enum RequesDataType {
  137. Text,
  138. // 如果WebApi设置接收类型为[FromBody]String,需将数据先转义为String
  139. // 如:SendData:"data", 转义:"\"data\""
  140. StringText,
  141. Byte
  142. }
  1. /// <summary>
  2. /// Stream扩展类
  3. /// </summary>
  4. public static class StreamEx {
  5. /// <summary>
  6. /// 流转字符串
  7. /// </summary>
  8. /// <param name="stream"></param>
  9. /// <param name="encoding"></param>
  10. /// <returns></returns>
  11. public static string ReadText(this Stream stream, Encoding encoding) {
  12. string text = string.Empty;
  13. using(StreamReader streamReader = new StreamReader(stream, encoding)) {
  14. text = streamReader.ReadToEnd();
  15. }
  16. return text;
  17. }
  18. /// <summary>
  19. /// 流转Gzip压缩字符串
  20. /// </summary>
  21. /// <param name="stream"></param>
  22. /// <param name="encoding"></param>
  23. /// <returns></returns>
  24. public static string ReadGzipText(this Stream stream, Encoding encoding) {
  25. string text = string.Empty;
  26. using(GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress)) {
  27. using(StreamReader reader = new StreamReader(gZipStream, encoding)) {
  28. text = reader.ReadToEnd();
  29. }
  30. }
  31. return text;
  32. }
  33. }
  1. public Form1() {
  2. InitializeComponent();
  3. Init();
  4. }
  5. DataTable dt_head = new DataTable();
  6. void Init() {
  7. cb_requetType.SelectedIndex = 0;
  8. dt_head.Columns.Add("key");
  9. dt_head.Columns.Add("value");
  10. grid_headers.DataSource = dt_head;
  11. }
  12. private void btn_send_Click(object sender, EventArgs e) {
  13. WebHeaderCollection headrs = new WebHeaderCollection();
  14. foreach(DataRow row in dt_head.Rows) {
  15. headrs.Add(row[0].ToString(), row[1].ToString());
  16. }
  17. HttpItem httpItem = new HttpItem(text_url.Text, requestData: text_params.Text) {
  18. Header = headrs,
  19. Method = cb_requetType.Text == "Get" ? RequestMethod.GET : RequestMethod.POST
  20. };
  21. HttpResult httpResult = HttpUtil.HttpRequest(httpItem);
  22. if(httpResult.Status) {
  23. text_response.Text = httpResult.HttpStringData;
  24. }
  25. else {
  26. text_response.Text = "error:" + httpResult.Msg;
  27. }
  28. }

实现效果:

由简入繁,拿来即用

更多精彩,请搜索公众号:Csharp 小记

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/259692
推荐阅读
相关标签
  

闽ICP备14008679号