csharp HttpHelper类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp HttpHelper类相关的知识,希望对你有一定的参考价值。

public class HttpHelp
{
    public CookieContainer CookieContainer { get; set; }

    public CookieCollection CookieCollection { get; set; }

    public HttpHelp()
    {
        this.CookieCollection = new CookieCollection();
        this.CookieContainer = new CookieContainer();
    }

    public static string GetHtml(string url, string Referer, Encoding encode)
    {
        return new HttpHelp().GetHtml(url, Referer, encode, false);
    }

    public static string PostHtml(string url, string Referer, string data, Encoding encode)
    {
        return new HttpHelp().PostHtml(url, Referer, data, encode, false);
    }

    public string GetHtml(string url, string Referer, Encoding encode, bool SaveCookie)
    {
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.Method = "GET";
        req.CookieContainer = this.CookieContainer;
        req.Proxy = null;
        if (!string.IsNullOrEmpty(Referer))
            req.Referer = Referer;
        using (HttpWebResponse hwr = req.GetResponse() as HttpWebResponse)
        {
            if (SaveCookie)
            {
                this.CookieCollection = hwr.Cookies;
                this.CookieContainer.GetCookies(req.RequestUri);
            }
            using (StreamReader SR = new StreamReader(hwr.GetResponseStream(), encode))
            {
                return SR.ReadToEnd();
            }
        }
    }

    public string PostHtml(string url, string Referer, string data, Encoding encode, bool SaveCookie)
    {
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.CookieContainer = this.CookieContainer;
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        req.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0";
        req.Proxy = null;
        req.ProtocolVersion = HttpVersion.Version10;
        if (!string.IsNullOrEmpty(Referer))
            req.Referer = Referer;
        byte[] mybyte = Encoding.Default.GetBytes(data);
        req.ContentLength = mybyte.Length;
        using (Stream stream = req.GetRequestStream())
        {
            stream.Write(mybyte, 0, mybyte.Length);
        }
        using (HttpWebResponse hwr = req.GetResponse() as HttpWebResponse)
        {
            if (SaveCookie)
            {
                this.CookieCollection = hwr.Cookies;
                this.CookieContainer.GetCookies(req.RequestUri);
            }
            using (StreamReader SR = new StreamReader(hwr.GetResponseStream(), encode))
            {
                return SR.ReadToEnd();
            }
        }
    }

    ///
    /// 上传文件
    ///
    ///上传地址
    ///文件路径
    ///原网页file控件name
    ///请求流中的contentType
    ///返回的encoding
    ///post参数字典
    ///
    public static string PostFile(string url, string filepath, string paramName, string contentType, Encoding encode, Dictionary<string, string> dict)
    {
        HttpWebRequest hrq = WebRequest.Create(url) as HttpWebRequest;
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.Default.GetBytes("\r\n--" + boundary + "\r\n");
        hrq.ContentType = "multipart/form-data; boundary=" + boundary;
        hrq.Method = "POST";

        using (Stream stream = hrq.GetRequestStream())  //请求流
        {
            //写入post参数
            string formdataTemplete = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            if (dict != null && dict.Count > 0)
            {
                foreach (KeyValuePair<string, string> pair in dict)
                {
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem = string.Format(formdataTemplete, pair.Key, pair.Value);
                    byte[] formitemBytes = Encoding.Default.GetBytes(formitem);
                    stream.Write(formitemBytes, 0, formitemBytes.Length);
                }
            }
            stream.Write(boundarybytes, 0, boundarybytes.Length);

            //写入头信息
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, Path.GetFileName(filepath), contentType);
            byte[] headerBytes = Encoding.UTF8.GetBytes(header);
            stream.Write(headerBytes, 0, headerBytes.Length);

            //写入文件
            byte[] fileBytes = File.ReadAllBytes(filepath);
            stream.Write(fileBytes, 0, fileBytes.Length);

            //写入尾部
            byte[] footerBytes = Encoding.Default.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(footerBytes, 0, footerBytes.Length);

            using (HttpWebResponse hrp = hrq.GetResponse() as HttpWebResponse)//响应流
            {
                using (StreamReader SR = new StreamReader(hrp.GetResponseStream(), encode))
                {
                    return SR.ReadToEnd();
                }
            }
        }
    }
}

以上是关于csharp HttpHelper类的主要内容,如果未能解决你的问题,请参考以下文章

HttpHelper工具类

HttpHelper类及调用

抓取百万知乎用户信息之HttpHelper的迭代之路

HttpHelper之我见

HttpHelper Http/Https请求方式

HttpHelper