当前位置: 首页 > 工具软件 > httphelper > 使用案例 >

一个很好的HttpHelper类 C# ASP.NET

太叔望
2023-12-01
名人名言:生活的理想,就是为了理想的生活。——张闻天 
之前我写过篇关于C# HttpWebRequest 特技的文章 疏忽证书的办法请在篇文章里面查找感谢,以下不做疏忽证书的办法

无论是Get还是Post 带Cookie,编码题目解决 ,这里完全做到了疏忽编码的题目

比来把上方的办法收拾了一下,这个类相当于一个SqlHelper类一下,我把它叫做HttpHelper类,今后还会慢慢更新,欲望大师多我支撑,

给大师分享一下吧,不好的处所感激大师留言斧正,不久不多说了上代码吧!


/// <summary>
/// 类申明:HttpHelps类,用来实现Http接见,Post或者Get体式格式的,直接接见,带Cookie的,带证书的等体式格式
/// 编码日期:2011-08-20
/// 编 码 人:  苏飞
/// 接洽体式格式:361983679  Email:sufei.1013@163.com  Blogs:http://sufei.cnblogs.com
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;
using _7c.BaseFunction;

public class HttpHelps
{
    #region 预定义办法或者变革

    //默认的编码
    private Encoding encoding = Encoding.Default;
    //HttpWebRequest对象用来创议恳求
    private HttpWebRequest request = null;
    //获取影响流的数据对象
    private HttpWebResponse response = null;
    //读取流的对象
    private StreamReader reader = null;
    //须要返回的数据对象
    private string returnData = "String Error";

    /// <summary>
    /// 按拍照传入的数据,获得响应页面数据
    /// </summary>
    /// <param name="strPostdata">传入的数据Post体式格式,get体式格式传NUll或者空字符串都可以</param>
    /// <returns>string类型的响应数据</returns>
    private string GetHttpRequestData(string strPostdata)
    {
        try
        {
            //支撑跳转页面,查询成果将是跳转后的页面
            request.AllowAutoRedirect = true;

            //验证在获得成果时是否有传入数据
            if (!string.IsNullOrEmpty(strPostdata) && request.Method.Trim().ToLower().Contains("post"))
            {
                byte[] buffer = encoding.GetBytes(strPostdata);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
            }

            #region 获得恳求的response

            using (response = (HttpWebResponse)request.GetResponse())
            {
                //从这里开端我们要疏忽编码了
                if (encoding == null)
                {
                    MemoryStream _stream = new MemoryStream();
                    response.GetResponseStream().CopyTo(_stream, 10240);
                    byte[] RawResponse = _stream.ToArray();
                    string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
                    //<meta(.*?)charset([\s]?)=[^>](.*?)>
                    Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"""]", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
                    charter = charter.Replace("\"", string.Empty).Replace("""", string.Empty).Replace(";", string.Empty);
                    if (charter.Length > 0)
                    {
                        encoding = Encoding.GetEncoding(charter);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(response.CharacterSet))
                        {
                            encoding = Encoding.UTF8;
                        }
                        else
                        {
                            encoding = Encoding.GetEncoding(response.CharacterSet);
                        }
                    }
                    returnData = encoding.GetString(RawResponse);
                }
                else
                {
                    //开端读取流并设置编码体式格式
                    using (reader = new StreamReader(response.GetResponseStream(), encoding))
                    {
                        returnData = reader.ReadToEnd();
                    }
                }
            }

            #endregion
        }
        catch (Exception)
        {
            //这里是在产生异常时返回的错误信息
            returnData = "String Error";
        }
        return returnData.ToLower();
    }

    /// <summary>
    /// 为恳求筹办参数
    /// </summary>
    /// <param name="_URL">恳求的URL地址</param>
    /// <param name="_Method">恳求体式格式Get或者Post</param>
    /// <param name="_Accept">Accept</param>
    /// <param name="_ContentType">ContentType返回类型</param>
    /// <param name="_UserAgent">UserAgent客户端的接见类型,包含浏览器版本和操纵体系信息</param>
    /// <param name="_Encoding">读取数据时的编码体式格式</param>
    private void SetRequest(string _URL, string _Method, string _Accept, string _ContentType, string _UserAgent, Encoding _Encoding)
    {
        //初始化对像,并设置恳求的URL地址
        request = (HttpWebRequest)WebRequest.Create(FunctionServices.GetUrl(_URL));
        //恳求体式格式Get或者Post
        request.Method = _Method;
        //Accept
        request.Accept = _Accept;
        //ContentType返回类型
        request.ContentType = _ContentType;
        //UserAgent客户端的接见类型,包含浏览器版本和操纵体系信息
        request.UserAgent = _UserAgent;
        //读取数据时的编码体式格式
        encoding = _Encoding;
    }

    #endregion

    #region 通俗类型

    /// <summary>
    /// 采取https和谈GET|POST体式格式接见收集,按照传入的URl地址,获得响应的数据字符串。
    /// </summary>
    /// <param name="_URL"></param>
    /// <param name="_Method">恳求体式格式Get或者Post</param>
    /// <param name="_Accept">Accept</param>
    /// <param name="_ContentType">ContentType返回类型</param>
    /// <param name="_UserAgent">UserAgent客户端的接见类型,包含浏览器版本和操纵体系信息</param>
    /// <param name="_Encoding">读取数据时的编码体式格式</param>
    /// <param name="_Postdata">只有_Method为Post体式格式时才须要传入值</param>
    /// <returns>返回Html源代码</returns>
    public string GetHttpRequestString(string _URL, string _Method, string _Accept, string _ContentType, string _UserAgent, Encoding _Encoding, string _Postdata)
    {
        //筹办参数
        SetRequest(_URL, _Method, _Accept, _ContentType, _UserAgent, _Encoding);
        //调用专门读取数据的类
        return GetHttpRequestData(_Postdata);
    }

    ///<summary>
    ///采取https和谈GET体式格式接见收集,按照传入的URl地址,获得响应的数据字符串。
    ///</summary>
    ///<param name="URL">url地址</param>
    ///<param name="objencoding">编码体式格式例如:System.Text.Encoding.UTF8;</param>
    ///<returns>String类型的数据</returns>
    public string GetHttpRequestStringByNUll_Get(string URL, Encoding objencoding)
    {
        //筹办参数
        SetRequest(URL, "GET", "text/html, application/xhtml+xml, */*", "text/html", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", objencoding);
        //调用专门读取数据的类
        return GetHttpRequestData("");
    }

    ///<summary>
    ///采取https和谈GET体式格式接见收集,按照传入的URl地址,获得响应的数据字符串。
    ///</summary>
    ///<param name="URL">url地址</param>
    ///<param name="objencoding">编码体式格式例如:System.Text.Encoding.UTF8;</param>
    ///<param name="stgrcookie">Cookie字符串</param>
    ///<returns>String类型的数据</returns>
    public string GetHttpRequestStringByNUll_GetBycookie(string URL, Encoding objencoding, string stgrcookie)
    {
        //筹办参数
        SetRequest(URL, "GET", "text/html, application/xhtml+xml, */*", "text/html", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", objencoding);
        request.Headers[HttpRequestHeader.Cookie] = stgrcookie;
        //调用专门读取数据的类
        return GetHttpRequestData("");
    }

    ///<summary>
    ///采取https和谈GET体式格式接见收集,按照传入的URl地址,获得响应的数据字符串。
    ///</summary>
    ///<param name="URL">url地址</param>
    ///<param name="objencoding">编码体式格式例如:System.Text.Encoding.UTF8;</param>
    ///<returns>String类型的数据</returns>
    public string GetHttpRequestStringByNUll_Get(string URL, Encoding objencoding, string _Accept, string useragent)
    {
        //筹办参数
        SetRequest(URL, "GET", _Accept, "text/html", useragent, objencoding);
        //调用专门读取数据的类
        return GetHttpRequestData("");
    }

    ///<summary>
    ///采取https和谈Post体式格式接见收集,按照传入的URl地址,获得响应的数据字符串。
    ///</summary>
    ///<param name="URL">url地址</param>
    ///<param name="strPostdata">Post发送的数据</param>
    ///<param name="objencoding">编码体式格式例如:System.Text.Encoding.UTF8;</param>
    ///<returns>String类型的数据</returns>
    public string GetHttpRequestStringByNUll_Post(string URL, string strPostdata, Encoding objencoding)
    {
        //筹办参数
        SetRequest(URL, "post", "text/html, application/xhtml+xml, */*", "text/html", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", objencoding);
        //调用专门读取数据的类
        return GetHttpRequestData(strPostdata);
    }

    #endregion
}



在很多景象下我们会应用间过程的webBrowser去实现一些网页的恳乞降抓去,这个时辰有项目组网页是取不到Cookie的,那怎么办呢?下面我供给一个办法,应当99%的都能取到,


 //取当前webBrowser登录后的Cookie值
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref int pcchCookieData, int dwFlags, object lpReserved);

        //取出Cookie,当登录后才干取
        private static string GetCookieString(string url)
        {
            // Determine the size of the cookie     
            int datasize = 256;
            StringBuilder cookieData = new StringBuilder(datasize);
            if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0 x00002000, null))
            {
                if (datasize < 0)
                    return null;
                // Allocate stringbuilder large enough to hold the cookie     
                cookieData = new StringBuilder(datasize);
                if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0 x00002000, null))
                    return null;
            }
            return cookieData.ToString();
        }




                         

         迎接大师转载,如有转载请注明文章来自:   http://sufei.cnblogs.com/   

 类似资料: