C#-Http协议通讯(三)-HttpWebRequest


/** *┌──────────────────────────────────────────────────────────────┐ *│ 描 述: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; } } }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM