C# HTTP网络常用方法封装

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace Register  
  7. {  
  8.     public class HttpClass  
  9.     {  
  10.         private System.Net.HttpWebRequest Request = null;  
  11.         private System.Net.WebResponse Response = null;  
  12.         private System.IO.Stream Stream = null;  
  13.         private System.IO.StreamReader Read = null;  
  14.         private System.Byte[] Byte = null;  
  15.         private System.Text.Encoding Encode = System.Text.Encoding.UTF8;  
  16.         private System.Text.RegularExpressions.Match Match = null;  
  17.         /// <summary>  
  18.         /// 公开属性  
  19.         /// </summary>  
  20.         public System.Net.WebProxy Proxy = new System.Net.WebProxy()  
  21.         public string IPFor = null;  
  22.         public bool HideInfo = false;  
  23.         /// <summary>  
  24.         /// 初始化Request  
  25.         /// </summary>  
  26.         /// <param name="Request">对象</param>  
  27.         private void init_Request(ref System.Net.HttpWebRequest Request)  
  28.         {  
  29.             //终端信息  
  30.             Request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,image/png,application/java-archive,application/java,application/x-java-archive,text/vnd.sun.j2me.app-descriptor,application/vnd.oma.drm.message,application/vnd.oma.drm.content,application/vnd.oma.dd+xml,application/vnd.oma.drm.rights+xml,application/vnd.oma.drm.rights+wbxml,application/x-nokia-widget,text/x-opml,application/vnd.nokia.headwrapper,*/*;q=0.5";  
  31.             Request.Headers.Add("Accept-Charset""iso-8859-1,utf-8;q=0.7,*;q=0.7");  
  32.             Request.Headers.Add("Accept-Language""zh-cn, zh;q=1.0,en;q=0.5,en;q=0.5,en;q=0.5");  
  33.             Request.Headers.Add("Accept-Encoding""gzip, deflate, x-gzip, identity; q=0.9");  
  34.             Request.Headers.Add("X-Nokia-MusicShop-Version""11.0842.9");  
  35.             //承载方式  
  36.             Request.Headers.Add("X-Nokia-MusicShop-Bearer""GPRS/3G");  
  37.             Request.Headers.Add("X-Nokia-CONNECTION_MODE""TCP");  
  38.             Request.Headers.Add("X-Nokia-BEARER""3G");  
  39.             Request.Headers.Add("x-up-bear-type""GPRS/EDGE");  
  40.             Request.Headers.Add("X-Up-Bearer-Type""GPRS");  
  41.             //GGSN信息  
  42.             Request.Headers.Add("x-source-id""GZGGSN1101BEr");  
  43.             Request.Headers.Add("Client-IP""211.139.151.74");  
  44.             if (IPFor != null) Request.Headers.Add("x-forwarded-for", IPFor);  
  45.             //网关信息  
  46.             Request.Headers.Add("Via""WTP/1.1 192.168.13.33 (Nokia WAP Gateway 4.1/CD1/ECD13_E/4.1.05)");  
  47.             Request.Headers.Add("X-Nokia-gateway-id""NWG/4.1/Build4.1.05");  
  48.             //目标主机  
  49.             Request.Headers.Add("X-Online-Host", Request.Host);  
  50.             //重要信息  
  51.             if (!HideInfo)  
  52.             {  
  53.                 Request.UserAgent = "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5230/10.0.055; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413";  
  54.                 Request.Headers.Add("x-wap-profile""http://nds1.nds.nokia.com/uaprof/Nokia5230r100-3G.xml")  
  55.                 if (IPFor != null)  
  56.                 {  
  57.                     Request.Headers.Add("x-nokia-ipaddress", IPFor);  
  58.                 }  
  59.             }  
  60.             //自动重定向  
  61.             Request.AllowAutoRedirect = false;  
  62.             //代理设置  
  63.             if (Proxy.Address != null)  
  64.             {  
  65.                 Request.Proxy = Proxy;  
  66.             }  
  67.             //其它杂项  
  68.             Request.KeepAlive = false;  
  69.             Request.Timeout = 8000;  
  70.         }  
  71. //         public void GZipDecompress(ref System.IO.Stream refStream)  
  72. //         {  
  73. //             using (System.IO.MemoryStream stream = new System.IO.MemoryStream())  
  74. //             {  
  75. //                 using (System.IO.Compression.GZipStream gZip = new System.IO.Compression.GZipStream(refStream, System.IO.Compression.CompressionMode.Decompress, true))  
  76. //                 {  
  77. //                     System.IO.BinaryReader reader = new System.IO.BinaryReader(gZip);  
  78. //                     System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);  
  79. //                     while (true)  
  80. //                     {  
  81. //                         char[] p = reader.ReadChars(32);  
  82. //                         byte[] buffer = reader.ReadBytes(32);  
  83. //                         if (buffer == null || buffer.Length < 1) break;  
  84. //                         writer.Write(buffer);  
  85. //                     }  
  86. //                     writer.Close();  
  87. //                     gZip.CopyTo(stream);  
  88. //                 }  
  89. //                 stream.CopyTo(refStream);  
  90. //             }  
  91. //         }  
  92.         /// <summary>  
  93.         /// 获取网页数据  
  94.         /// </summary>  
  95.         /// <param name="url">请求地址</param>  
  96.         /// <returns>失败返回null</returns>  
  97.         public string get_Internet(string url, string cookie = null)  
  98.         {  
  99.             try  
  100.             {  
  101.                 Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);  
  102.                 url = null;  
  103.                 if (Request != null)  
  104.                 {  
  105.                     init_Request(ref Request);  
  106.                     if (cookie != null) { Request.Headers.Add("Cookie", cookie); }  
  107.                     using (Response = Request.GetResponse())  
  108.                     {  
  109.                         Stream = Response.GetResponseStream();  
  110.                         using (Read = new System.IO.StreamReader(Stream, System.Text.Encoding.UTF8))  
  111.                         {  
  112.                             url = Read.ReadToEnd();  
  113.                         }  
  114.                         Read = null;  
  115.                         Stream = null;  
  116.                     }  
  117.                     Response = null;  
  118.                     Request.Abort();   
  119.                     Request = null;  
  120.                 }  
  121.                 return url;  
  122.             }  
  123.             catch(Exception ex)  
  124.             {  
  125.                 Error.Write(ref ex);  
  126.                 return null;  
  127.             }  
  128.         }  
  129.         /// <summary>  
  130.         /// 获取数据流  
  131.         /// </summary>  
  132.         /// <param name="url">地址</param>  
  133.         /// <param name="Stream">返回数据流</param>  
  134.         /// <returns>失败为false</returns>  
  135.         public bool get_Stream(string url, ref System.IO.MemoryStream Stream, ref string cookie)  
  136.         {  
  137.             try  
  138.             {  
  139.                 Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);  
  140.                 init_Request(ref Request);  
  141.                 if (cookie != null) { Request.Headers.Add("Cookie", cookie); }  
  142.                 using (Response = Request.GetResponse())  
  143.                 {  
  144.                     Response.GetResponseStream().CopyTo(Stream);  
  145.                     if (cookie != null)  
  146.                     {  
  147.                         cookie += " " + get_Match(Response.Headers.Get("Set-Cookie"), "verifysession=([^;]+);").Replace(";""");  
  148.                     }  
  149.                 }  
  150.                 Response = null;  
  151.             }  
  152.             catch (Exception ex)  
  153.             {  
  154.                 Error.Write(ref ex);  
  155.                 return false;  
  156.             }  
  157.             if (Request != null)  
  158.             {  
  159.                 Request.Abort();  
  160.                 Request = null;  
  161.             }  
  162.             return true;  
  163.         }  
  164.         /// <summary>  
  165.         /// 提交数据并获取返回数据  
  166.         /// </summary>  
  167.         /// <param name="url">请求地址</param>  
  168.         /// <returns>失败返回null</returns>  
  169.         public string post_Internet(string url, string data, string cookie = null)  
  170.         {  
  171.             try  
  172.             {  
  173.                 Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);  
  174.                 url = null;  
  175.                 if (Request != null)  
  176.                 {  
  177.                     init_Request(ref Request);  
  178.                     if (cookie != null) { Request.Headers.Add("Cookie", cookie); }  
  179.                     Request.Method = "POST";  
  180.                     Request.ServicePoint.Expect100Continue = false;  
  181.                     Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";  
  182.                     Byte = Encode.GetBytes(data);  
  183.                     Request.ContentLength = Byte.Length;  
  184.                     using (Stream = Request.GetRequestStream())  
  185.                     {  
  186.                         Stream.Write(Byte, 0, Byte.Length);  
  187.                     }  
  188.                     Stream = null;  
  189.                     Byte = null;  
  190.                     data = null;  
  191.                     using (Response = Request.GetResponse())  
  192.                     {  
  193.                         Stream = Response.GetResponseStream();  
  194.                         using (Read = new System.IO.StreamReader(Stream))  
  195.                         {  
  196.                             url = Read.ReadToEnd();  
  197.                         }  
  198.                         Read = null;  
  199.                         Stream = null;  
  200.                     }  
  201.                     Response = null;  
  202.                     Request.Abort();  
  203.                     Request = null;  
  204.                 }  
  205.                 return url;  
  206.             }  
  207.             catch (Exception ex)  
  208.             {  
  209.                 Error.Write(ref ex);  
  210.                 return null;  
  211.             }         
  212.         }  
  213.         /// <summary>  
  214.         /// 获取服务器响应报文信息  
  215.         /// </summary>  
  216.         /// <param name="url">请求地址</param>  
  217.         /// <returns>HTTP响应报文</returns>  
  218.         public string get_All(string url, string cookie = null)  
  219.         {  
  220.             try  
  221.             {  
  222.                 Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);  
  223.                 url = null;  
  224.                 if (Request != null)  
  225.                 {  
  226.                     Request.Method = "GET";  
  227.                     init_Request(ref Request);  
  228.                     if (cookie != null) { Request.Headers.Add("Cookie", cookie); }  
  229.                     using (Response = Request.GetResponse())  
  230.                     {  
  231.                         foreach (string name in Response.Headers.AllKeys)  
  232.                         {  
  233.                             url += name + "=" + Response.Headers.Get(name) + "; ";  
  234.                         }  
  235.                         Stream = Response.GetResponseStream();  
  236.                         using (Read = new System.IO.StreamReader(Stream, System.Text.Encoding.UTF8))  
  237.                         {  
  238.                             url += Read.ReadToEnd();  
  239.                         }  
  240.                         Read = null;  
  241.                         Stream = null;  
  242.                     }  
  243.                     Response = null;  
  244.                     Request.Abort();  
  245.                     Request = null;  
  246.                 }  
  247.                 return url;  
  248.             }  
  249.             catch (Exception ex)  
  250.             {  
  251.                 Error.Write(ref ex);  
  252.                 return null;  
  253.             }  
  254.         }  
  255.         /// <summary>  
  256.         /// 获取服务器返回信息  
  257.         /// </summary>  
  258.         /// <param name="url">请求地址</param>  
  259.         /// <returns>HTTP Header</returns>  
  260.         public string get_Header(string url, string key = "Set-Cookie"string cookie = null)  
  261.         {  
  262.             try  
  263.             {  
  264.                 Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);  
  265.                 url = null;  
  266.                 if (Request != null)  
  267.                 {  
  268.                     Request.Method = "HEAD";  
  269.                     init_Request(ref Request);  
  270.                     if (cookie != null) { Request.Headers.Add("Cookie", cookie); }  
  271.                     using (Response = Request.GetResponse())  
  272.                     {  
  273.                         url = Response.Headers.Get(key);  
  274.                     }  
  275.                     Response = null;  
  276.                     Request.Abort();  
  277.                     Request = null;  
  278.                 }  
  279.                 return url;  
  280.             }  
  281.             catch (Exception ex)  
  282.             {  
  283.                 Error.Write(ref ex);  
  284.                 return null;  
  285.             }  
  286.         }  
  287.           
  288.         /// <summary>  
  289.         /// 获取匹配信息  
  290.         /// </summary>  
  291.         /// <param name="src">匹配内容</param>  
  292.         /// <returns>正则表达式</returns>  
  293.         public string get_Match(string src, string pattern, string substr = null)  
  294.         {  
  295.             Match = System.Text.RegularExpressions.Regex.Match(src, pattern);  
  296.             if (!Match.Success)  
  297.             {  
  298.                 return null;  
  299.             }  
  300.             if (substr != null)  
  301.             {  
  302.                 return Match.Groups[substr].Value;  
  303.             }  
  304.             return Match.Value;  
  305.         }  
  306.         /// <summary>  
  307.         /// 发送邮件  
  308.         /// </summary>  
  309.         /// <param name="ToAddress"></param>  
  310.         /// <param name="Subject"></param>  
  311.         /// <param name="Value"></param>  
  312.         /// <param name="PathArray"></param>  
  313.         /// <returns></returns>  
  314.         public static bool try_Email(string ToAddress, string Subject, string Value, string[] PathArray = null)  
  315.         {  
  316.             bool result = false;  
  317.   
  318.             System.Net.Mail.SmtpClient Mail = new System.Net.Mail.SmtpClient("smtp.qq.com", 25);  
  319.             Mail.UseDefaultCredentials = true;  
  320.             Mail.Credentials = new System.Net.NetworkCredential("feedback01""z123456");  
  321.             Mail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;  
  322.   
  323.             System.Net.Mail.MailMessage Messages = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress("feedback01@qq.com"), new System.Net.Mail.MailAddress(ToAddress));  
  324.             Messages.BodyEncoding = System.Text.Encoding.UTF8;  
  325.             Messages.SubjectEncoding = System.Text.Encoding.UTF8;  
  326.             Messages.Subject = Subject;  
  327.             Messages.Body = Value;  
  328.   
  329.             System.Net.Mail.Attachment[] Attachments = null;  
  330.             try  
  331.             {  
  332.                 if (PathArray != null)  
  333.                 {  
  334.                     Attachments = new System.Net.Mail.Attachment[PathArray.Length];  
  335.   
  336.                     for (int i = 0; i < PathArray.Length; i++)  
  337.                     {  
  338.                         if (PathArray[i].Length >= 6 && System.IO.File.Exists(PathArray[i]))  
  339.                         {  
  340.                             Attachments[i] = new System.Net.Mail.Attachment(PathArray[i]);  
  341.                             Messages.Attachments.Add(Attachments[i]);  
  342.                         }  
  343.                     }  
  344.                 }  
  345.                 Mail.Send(Messages);  
  346.                 result = true;  
  347.             }  
  348.             catch(Exception ex)  
  349.             {  
  350.                 Error.Write(ref ex);  
  351.                 result = false;  
  352.             }  
  353.   
  354.             if (Attachments != null)  
  355.             {  
  356.                 for (int k = 0; k < Attachments.Length; k++)  
  357.                 {  
  358.                     if (Attachments[k] != null)  
  359.                     {  
  360.                         Attachments[k].Dispose();  
  361.                     }  
  362.                 }  
  363.             }  
  364.   
  365.             Messages.Dispose();  
  366.             Mail.Dispose();  
  367.   
  368.             return result;  
  369.         }  
  370.         /// <summary>  
  371.         /// 用于ShellExecuteEx  
  372.         /// </summary>  
  373.         [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]  
  374.         public struct SHELLEXECUTEINFO  
  375.         {  
  376.             public int cbSize;  
  377.             public int fMask;  
  378.             public int hwnd;  
  379.             [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]  
  380.             public string lpVerb;  
  381.             [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]  
  382.             public string lpFile;  
  383.             [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]  
  384.             public string lpParameters;  
  385.             public int lpDirectory;  
  386.             public int nShow;  
  387.             public int hInstApp;  
  388.             public int lpIDList;  
  389.             public int lpClass;  
  390.             public int hkeyClass;  
  391.             public int dwHotKey;  
  392.             public int hIcon;  
  393.             public int hProcess;  
  394.         }  
  395.         /// <summary>  
  396.         /// ShellExecuteEx  
  397.         /// </summary>  
  398.         /// <param name="lpExecInfo"></param>  
  399.         /// <returns></returns>  
  400.         [System.Runtime.InteropServices.DllImport("Shell32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]  
  401.         public static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);  
  402.         static SHELLEXECUTEINFO ShellInfo;  
  403.         /// <summary>  
  404.         /// 打开URL  
  405.         /// </summary>  
  406.         /// <param name="url"></param>  
  407.         public static void OpenURL(string url)  
  408.         {  
  409.             if (ShellInfo.lpFile == null)  
  410.             {  
  411.                 Microsoft.Win32.RegistryKey SubKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"HTTPshellopencommand");  
  412.                 if (SubKey == null)  
  413.                 {  
  414.                     return;  
  415.                 }  
  416.                 string Explorer = ((string)SubKey.GetValue(null)).Replace(""""");  
  417.                 int SpaceOffset = -1;  
  418.                 if ((SpaceOffset = Explorer.LastIndexOf(" ")) != -1)  
  419.                 {  
  420.                     Explorer = Explorer.Substring(0, SpaceOffset);  
  421.                 }  
  422.   
  423.                 ShellInfo.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(ShellInfo);  
  424.                 ShellInfo.lpFile = Explorer;  
  425.                 ShellInfo.nShow = 1; //SW_SHOWNORMAL  
  426.                 SubKey.Close();  
  427.                 SubKey.Dispose();  
  428.             }  
  429.             ShellInfo.lpParameters = url;  
  430.             ShellExecuteEx(ref ShellInfo);  
  431.         }  
  432.     }  
  433. }  
原文地址:https://www.cnblogs.com/codeloves/p/3365312.html