/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描    述:Http请求工具类
*│  Get     :像数据库的select,只是用来查询一下数据,不会修改、增加数据,不会影响资源的内容。
*│  Post    :像数据库的insert操作一样,会创建新的内容。几乎目前所有的提交操作都是用POST请求的。
*│  Put     :像数据库的update操作一样,用来修改数据的内容,但是不会增加数据的种类等。
*│  Delete  :像数据库的delete操作
*│ 作    者:执笔小白
*│ 版    本:2.1                                   
*│ 创建时间:2021-10-20 15:40:56~2023-03-25 22:42:56                            
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: WebserviceWcfWebAPITestTool.ASPNetCoreWebAPI_Test                             
*│ 类    名:WebAPITestForm                                     
*└──────────────────────────────────────────────────────────────┘
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using static System.Net.WebRequestMethods;

namespace CommonTools
{
    // 请求工具类
    // HttpWebRequest(WebRequest.Create):.NET.Framework的请求/响应模型的抽象基类,用于访问Internet数据。
    // HttpWebResponse:对http协议进行了完整的封装( Header, Content, Cookie),与HttpWebRequest结合使用。
    public class RequestCom
    {
        #region WebAPI
        /// <summary>
        /// Get方法
        /// </summary>
        /// 例如:http://localhost:30202/api/ValuesTest/Sum?num1=1&num2=3
        /// <param name="postData">后缀(?num1=1&num2=3)</param>
        /// <param name="Url">url(http://localhost:30202/api/ValuesTest/Sum)</param>
        /// <returns></returns>
        public static string GetInfo(string postData, string Url)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
                webRequest.Method = "GET";

                webRequest.ContentType = "application/json; charset=utf-8";
                webRequest.ContentLength = byteArray.Length;
                webRequest.Accept = "application/json, text/javascript, */*";

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd(); // 返回的数据
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="body">application/json</param>
        /// <returns></returns>
        public static string HttpPost(string url, string body)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(body);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json; charset=utf-8";
                webRequest.ContentLength = byteArray.Length;
                webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);
                webRequest.Accept = "application/json, text/javascript, */*";

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Put请求-必有body
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="body">application/json</param>
        /// <returns></returns>
        public static string HttpPut(string url, string body)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(body);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "PUT";
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = byteArray.Length;
                webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);
                webRequest.Accept = "application/json, text/javascript, */*";

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Delete请求-必有body
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="body">application/json</param>
        /// <returns></returns>
        public static string HttpDelete(string url, string body)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(body);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "DELETE";
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = byteArray.Length;
                webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);
                webRequest.Accept = "application/json, text/javascript, */*";

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion

        #region WebService

        /// <summary>
        /// Set
        /// </summary>

        /// <summary>
        /// Post方法-拼接Body组方式:ReqBody参数组(Key,Value)
        /// </summary>
        /// <param name="url">webService的URL</param>
        /// <param name="method">调用的方法</param>
        /// <param name="reqBodys">参数组合</param>
        /// <returns></returns>
        public static string WebServiceHttpPost(string URL, string Method, List<ReqBody> ReqBodys, Encoding requestCoding, int timeout = 30000)
        {
            string param = string.Empty;
            switch (ReqBodys.Count)
            {
                case 0:
                    break;
                case 1:
                    param = HttpUtility.UrlEncode(ReqBodys[0].Key) + "=" + HttpUtility.UrlEncode(ReqBodys[0].Value);
                    break;
                default:
                    param = HttpUtility.UrlEncode(ReqBodys[0].Key) + "=" + HttpUtility.UrlEncode(ReqBodys[0].Value);
                    for (int i = 1; i < ReqBodys.Count; i++)
                    {
                        param += "&" + HttpUtility.UrlEncode(ReqBodys[i].Key) + "=" + HttpUtility.UrlEncode(ReqBodys[i].Value);
                    }
                    break;
            }
            //byte[] byteArray = Encoding.UTF8.GetBytes(param);
            byte[] byteArray = requestCoding.GetBytes(param);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(URL + "/" + Method);
            webRequest.Method = "POST";
            webRequest.Timeout = timeout;
            // webRequest.UserAgent = "DefaultUserAgent";
            webRequest.ContentType = "application/x-www-form-urlencoded";  // 浏览器默认的编码格式
            webRequest.ContentLength = byteArray.Length;
            webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);       //把参数数据写入请求数据的Stream对象

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();      //获得响应

            #region 只返回Response的Xml报文(Body内容)
            using (XmlTextReader reader = new XmlTextReader(webResponse.GetResponseStream()))  //获取响应流
            {
                reader.MoveToContent();
                return reader.ReadInnerXml();
            }
            #endregion 只返回Response的Xml报文(Body内容)

            #region 返回所有Xml报文
            //using(StreamReader sr = new StreamReader(webResponse.GetResponseStream(), requestCoding))
            //{
            //    return sr.ReadToEnd();
            //}
            #endregion 返回所有Xml报文
        }

        /// <summary>
        /// Post方法-拼接xml方式
        /// 下面有示例"Post方法-拼接xml方式示例"
        /// </summary>
        /// <param name="url">webService的URL</param>
        /// <param name="soapAction">soap方法,可为null</param>
        /// <param name="soap_Namespace">soap的命名空间</param>
        /// <param name="soap_EnvelopeXml">soap:Envelope的信息</param>
        /// <param name="soap_HeaderXml">soap:Header的信息</param>
        /// <param name="soap_BodyXml">soap:Body的信息</param>
        /// <param name="requestCoding">编码格式</param>
        /// <param name="timeout">超时</param>
        /// <returns></returns>
        public static string WebServiceHttpPost(string url, string soapAction, string soap_Namespace, string soap_EnvelopeXml, string soap_HeaderXml, string soap_BodyXml, Encoding requestCoding, int timeout = 30000)
        {
            // 确认编码
            string requestCodingStr = "UTF-8";
            switch (requestCoding)
            {
                case UTF8Encoding:
                    requestCodingStr = "UTF-8";
                    break;
                case UTF32Encoding:
                    requestCodingStr = "UTF-32";
                    break;
                case ASCIIEncoding:
                    requestCodingStr = "ASCII";
                    break;
                default:
                    break;
            }

            string requestXml = GetPostStr(requestCodingStr, soap_Namespace, soap_EnvelopeXml, soap_HeaderXml, soap_BodyXml);  // 拼接xml
            //byte[] byteArray = Encoding.UTF8.GetBytes(requestXml);
            byte[] byteArray = requestCoding.GetBytes(requestXml);

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = timeout;
            //httpWebRequest.ContentType = "application/x-www-form-urlencoded";  // 浏览器默认的编码格式
            httpWebRequest.ContentType = $"text/xml;charset={requestCodingStr}";  // xml编码格式
            if (soapAction != null)
            {
                httpWebRequest.Headers.Add("SOAPAction", soapAction);  // SOAP方法,有的需要设置(SOAP 1.1不一定需要;SOAP1.2不需要设置)
            }
            //httpWebRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5");
            //httpWebRequest.Headers.Add("Cache-Control", "no-cache");
            //httpWebRequest.UserAgent = "DefaultUserAgent";
            httpWebRequest.ContentLength = byteArray.Length;
            httpWebRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);       // 把参数数据写入请求数据的Stream对象

            // 接收返回信息
            HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            #region 只返回Response的Xml报文(Body内容)
            using (XmlTextReader reader = new XmlTextReader(webResponse.GetResponseStream()))  //获取响应流
            {
                reader.MoveToContent();
                return reader.ReadInnerXml();
            }
            #endregion 只返回Response的Xml报文(Body内容)

            #region 返回所有Xml报文
            //using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), requestCoding))  // 返回Xml格式的字符串
            //{
            //    return sr.ReadToEnd();
            //}
            #endregion 返回所有Xml报文
        }

        // Post方法-拼接xml方式示例
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    string soap_Namespace = "soap";
        //string soap_EnvelopeXml = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"";
        //string soap_HeaderXml = string.Empty;
        //string soap_BodyXml = " <HelloWorld xmlns=\"http://tempuri.org/\" />";
        //Encoding requestCoding = Encoding.UTF8;

        //string result = RequestCom.WebServiceHttpPost(url, soap_Namespace, soap_EnvelopeXml, soap_HeaderXml, soap_BodyXml, requestCoding);

        //textBox5.Text = result;
        //}

        /// <summary>
        /// 拼接HttpWebResponse的RequestStream
        /// </summary>
        /// <param name="requestCodingStr">编码格式</param>
        /// <param name="soap_Namespace">soap的命名空间</param>
        /// <param name="soap_EnvelopeXml">soap:Envelope的信息</param>
        /// <param name="soap_HeaderXml">soap:Header的信息</param>
        /// <param name="soap_BodyXml">soap:Body的信息</param>
        private static string GetPostStr(string requestCodingStr, string soap_Namespace, string soap_EnvelopeXml, string soap_HeaderXml, string soap_BodyXml)
        {
            // 拼接参数
            string postStr = string.Empty;

            postStr = $"<?xml version=\"1.0\" encoding=\"{requestCodingStr}\"?> ";
            // soap:Envelope的信息
            //<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
            //<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
            //<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tip=""http://www.digiwin.com.cn/tiptop/TIPTOPServiceGateWay"">
            postStr += $"<{soap_Namespace}:Envelope " + soap_EnvelopeXml + ">";

            // soap:Header的信息
            //<soap:Header></soap:Header>
            //<soap12:Header></soap12:Header>
            //<soapenv:Header></soapenv:Header>
            postStr += $"<{soap_Namespace}:Header>" + soap_HeaderXml + $"</{soap_Namespace}:Header>";

            // soap:Body的信息
            //<soap12:Body>
            //<HelloWorld xmlns="http://tempuri.org/" />
            //</soap12:Body>
            postStr += $"<{soap_Namespace}:Body>" + soap_BodyXml + $"</{soap_Namespace}:Body>";

            postStr += $"</{soap_Namespace}:Envelope>";
            return postStr;
        }
        #endregion WebService
    }

    // 参数
    public class ReqBody
    {
        /// <summary>
        /// 参数名
        /// </summary>
        public string Key { get; set; }

        /// <summary>
        /// 参数值
        /// </summary>
        public string Value { get; set; }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
  • 258.
  • 259.
  • 260.
  • 261.
  • 262.
  • 263.
  • 264.
  • 265.
  • 266.
  • 267.
  • 268.
  • 269.
  • 270.
  • 271.
  • 272.
  • 273.
  • 274.
  • 275.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280.
  • 281.
  • 282.
  • 283.
  • 284.
  • 285.
  • 286.
  • 287.
  • 288.
  • 289.
  • 290.
  • 291.
  • 292.
  • 293.
  • 294.
  • 295.
  • 296.
  • 297.
  • 298.
  • 299.
  • 300.
  • 301.
  • 302.
  • 303.
  • 304.
  • 305.
  • 306.
  • 307.
  • 308.
  • 309.
  • 310.
  • 311.
  • 312.
  • 313.
  • 314.
  • 315.
  • 316.
  • 317.
  • 318.
  • 319.
  • 320.
  • 321.
  • 322.
  • 323.
  • 324.
  • 325.
  • 326.
  • 327.
  • 328.
  • 329.
  • 330.
  • 331.
  • 332.
  • 333.
  • 334.
  • 335.
  • 336.
  • 337.
  • 338.
  • 339.
  • 340.
  • 341.
  • 342.
  • 343.
  • 344.
  • 345.
  • 346.
  • 347.
  • 348.
  • 349.
  • 350.
  • 351.
  • 352.
  • 353.
  • 354.
  • 355.

作者:꧁执笔小白꧂