苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.4-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 4531|回复: 0

[例子] HttpHelper常用的HttpStatusCode状态码的输出方法

[复制链接]
发表于 2021-8-17 15:10:48 | 显示全部楼层 |阅读模式
HttpHelper常用的HttpStatusCode状态码的输出方法

[C#] 纯文本查看 复制代码
    /// <summary>
    /// 取状态
    /// </summary>
    /// <param name="httpStatusCode"></param>
    /// <returns></returns>
    public string GetStat(HttpStatusCode httpStatusCode, WebHeaderCollection header)
    {
        switch (httpStatusCode)
        {
            case HttpStatusCode.Accepted:
                return "(202)  " + HttpStatusCode.Accepted.ToString();
            case HttpStatusCode.Ambiguous:
                return "(300)  " + HttpStatusCode.Ambiguous.ToString();
            case HttpStatusCode.BadGateway:
                return "(502)  " + HttpStatusCode.BadGateway.ToString();
            case HttpStatusCode.BadRequest:
                return "(400)  " + HttpStatusCode.BadRequest.ToString();
            case HttpStatusCode.Conflict:
                return "(409)  " + HttpStatusCode.Conflict.ToString();
            case HttpStatusCode.Continue:
                return "(100)  " + HttpStatusCode.Continue.ToString();
            case HttpStatusCode.Created:
                return "(201)  " + HttpStatusCode.Created.ToString();
            case HttpStatusCode.ExpectationFailed:
                return "(417)  " + HttpStatusCode.ExpectationFailed.ToString();
            case HttpStatusCode.Forbidden:
                return "(403)  " + HttpStatusCode.Forbidden.ToString();
            case HttpStatusCode.Found:
                return "(302) 页面跳转:" + header["Location"].ToString();
            case HttpStatusCode.GatewayTimeout:
                return "(504)  " + HttpStatusCode.GatewayTimeout.ToString();
            case HttpStatusCode.Gone:
                return "(410)  " + HttpStatusCode.Gone.ToString();
            case HttpStatusCode.HttpVersionNotSupported:
                return "(505)  " + HttpStatusCode.HttpVersionNotSupported.ToString();
            case HttpStatusCode.InternalServerError:
                return "(500)  " + HttpStatusCode.InternalServerError.ToString();
            case HttpStatusCode.LengthRequired:
                return "(411)  " + HttpStatusCode.LengthRequired.ToString();
            case HttpStatusCode.MethodNotAllowed:
                return "(405)  " + HttpStatusCode.MethodNotAllowed.ToString();
            case HttpStatusCode.Moved:
                return "(301) 页面跳转:" + header["Location"].ToString();
            case HttpStatusCode.NoContent:
                return "(204)  " + HttpStatusCode.NoContent.ToString();
            case HttpStatusCode.NonAuthoritativeInformation:
                return "(203)  " + HttpStatusCode.NonAuthoritativeInformation.ToString();
            case HttpStatusCode.NotAcceptable:
                return "(406)  " + HttpStatusCode.NotAcceptable.ToString();
            case HttpStatusCode.NotFound:
                return "(404)  " + HttpStatusCode.NotFound.ToString();
            case HttpStatusCode.NotImplemented:
                return "(501)  " + HttpStatusCode.NotImplemented.ToString();
            case HttpStatusCode.NotModified:
                return "(304)  " + HttpStatusCode.NotModified.ToString();
            case HttpStatusCode.OK:
                return "(200)  " + HttpStatusCode.OK.ToString();
            case HttpStatusCode.PartialContent:
                return "(206)  " + HttpStatusCode.PartialContent.ToString();
            case HttpStatusCode.PaymentRequired:
                return "(402)  " + HttpStatusCode.PaymentRequired.ToString();
            case HttpStatusCode.PreconditionFailed:
                return "(412)  " + HttpStatusCode.PreconditionFailed.ToString();
            case HttpStatusCode.ProxyAuthenticationRequired:
                return "(407)  " + HttpStatusCode.ProxyAuthenticationRequired.ToString();
            case HttpStatusCode.RedirectKeepVerb:
                return "(307)  " + HttpStatusCode.RedirectKeepVerb.ToString();
            case HttpStatusCode.RedirectMethod:
                return "(303)  " + HttpStatusCode.RedirectMethod.ToString();
            case HttpStatusCode.RequestEntityTooLarge:
                return "(413)  " + HttpStatusCode.RequestEntityTooLarge.ToString();
            case HttpStatusCode.RequestTimeout:
                return "(408)  " + HttpStatusCode.RequestTimeout.ToString();
            case HttpStatusCode.RequestUriTooLong:
                return "(414)  " + HttpStatusCode.RequestUriTooLong.ToString();
            case HttpStatusCode.RequestedRangeNotSatisfiable:
                return "(416)  " + HttpStatusCode.RequestedRangeNotSatisfiable.ToString();
            case HttpStatusCode.ResetContent:
                return "(205)  " + HttpStatusCode.ResetContent.ToString();
            case HttpStatusCode.ServiceUnavailable:
                return "(503)  " + HttpStatusCode.ServiceUnavailable.ToString();
            case HttpStatusCode.SwitchingProtocols:
                return "(101)  " + HttpStatusCode.SwitchingProtocols.ToString();
            case HttpStatusCode.Unauthorized:
                return "(401)  " + HttpStatusCode.Unauthorized.ToString();
            case HttpStatusCode.UnsupportedMediaType:
                return "(415)  " + HttpStatusCode.UnsupportedMediaType.ToString();
            case HttpStatusCode.Unused:
                return "(306)  " + HttpStatusCode.Unused.ToString();
            case HttpStatusCode.UseProxy:
                return "(305)  " + HttpStatusCode.UseProxy.ToString();
            default:
                return "无状态";
        }
    }


这个是最早期的Httphelper的写法中的方法,现在已经不在使用,大家可以自行处理

正好在这里给大家分享一个我10年前写的Httphelper类的原型

当时的想法是使用方法重载的方式来写,没有想过使用对象的方式,重载了很多方法
有兴趣的可以看看
[C#] 纯文本查看 复制代码
/// <summary>
/// 类说明:HttpHelps类,用来实现Http访问,Post或者Get方式的,直接访问,带Cookie的,带证书的等方式,可以设置代理
/// 编码日期:2011-08-20
/// 编 码 人:  苏飞
/// 联系方式:361983679  Email:[email]sufei.1013@163.com[/email]  Blogs:[url]http://sufei.cnblogs.com[/url]
/// 修改日期:2011-12-30
/// </summary>
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;
using System.Linq;


public class HttpHelps
{
    #region 预定义方法或者变更

    //默认的编码
    public Encoding encoding = Encoding.Default;
    //HttpWebRequest对象用来发起请求
    public HttpWebRequest request = null;
    //获取影响流的数据对象
    public HttpWebResponse response = null;
    //
    public Boolean AllowAutoRedirect = true;

    //Http头
    public WebHeaderCollection headers = new WebHeaderCollection();

    //状态检查
    public HttpStatusCode resultStatus = HttpStatusCode.OK;

    public Boolean isToLower = true;
    //读取流的对象
    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
        {
            //支持跳转页面,查询结果将是跳转后的页面
            if (AllowAutoRedirect)
            {
                request.AllowAutoRedirect = true;
            }
            else
            {
                request.AllowAutoRedirect = false;
            }

            //验证在得到结果时是否有传入数据
            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);
            }

            ////最大连接数
            //request.ServicePoint.ConnectionLimit = 1024;

            #region 得到请求的response

            using (response = (HttpWebResponse)request.GetResponse())
            {
                headers = response.Headers;
                resultStatus = response.StatusCode;
                //从这里开始我们要无视编码了
                if (encoding == null)
                {
                    Stream s = response.GetResponseStream();
                    if (response.ContentEncoding.ToLower().Contains("gzip"))
                        s = new GZipStream(s, CompressionMode.Decompress);
                    else if (response.ContentEncoding.ToLower().Contains("deflate"))
                        s = new DeflateStream(s, CompressionMode.Decompress);

                    MemoryStream _stream = new MemoryStream();
                    int bytesRead;
                    byte[] buffer = new byte[0x1000];
                    for (bytesRead = s.Read(buffer, 0, buffer.Length); bytesRead > 0; bytesRead = s.Read(buffer, 0, buffer.Length))
                    {
                        _stream.Write(buffer, 0, bytesRead);
                    }

                    byte[] RawResponse = _stream.ToArray();

                    string html = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length).Replace("\r\n","");
                    string charter = response.CharacterSet.ToUpper().Trim();

                    Match m = new Regex(@"<meta\b\s+.*?charset\b\s*=\s*[""|']?(?<charset>[^""]*)", RegexOptions.Singleline | RegexOptions.IgnoreCase).Match(html);

                    string htmlcharset = string.Empty;

                    if (m.Success)
                        htmlcharset = m.Groups["charset"].Value.Trim();

                    if (charter == "GB2312" || charter == "GBK")
                        encoding = Encoding.Default;
                    else if (RawResponse.Length > 3 && Convert.ToInt32(RawResponse[0]) == 239 && Convert.ToInt32(RawResponse[1]) == 187 && Convert.ToInt32(RawResponse[2]) == 191)
                        encoding = Encoding.UTF8;
                    else if (htmlcharset.Trim() != "")
                        encoding = Encoding.GetEncoding(htmlcharset);
                    else if (charter == "ISO-8859-1")
                        encoding = Encoding.Default;
                    else
                        encoding = Encoding.UTF8;

                    returnData = encoding.GetString(RawResponse);
                }
                else
                {
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //开始读取流并设置编码方式
                        using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
                        {
                            returnData = reader.ReadToEnd();
                        }
                    }
                    else
                    {
                        //开始读取流并设置编码方式
                        using (reader = new StreamReader(response.GetResponseStream(), encoding))
                        {
                            returnData = reader.ReadToEnd();
                        }
                    }
                }
            }

            #endregion
        }
        catch (WebException ex)
        {
            //这里是在发生异常时返回的错误信息
            returnData = "String Error";
            response = (HttpWebResponse)ex.Response;
            if (response == null || ex.Message.Contains("无法解析此远程名称"))
            {
                response = null;
            }
            else
            {
                headers = response.Headers;
                resultStatus = response.StatusCode;
            }

        }
        if (isToLower)
        {
            returnData = returnData.ToLower();
        }
        return returnData;
    }

    /// <summary>
    /// 4.0以下.net版本取水运
    /// </summary>
    /// <param name="streamResponse"></param>
    private static MemoryStream GetMemoryStream(Stream streamResponse)
    {
        MemoryStream _stream = new MemoryStream();
        int Length = 256;
        Byte[] buffer = new Byte[Length];
        int bytesRead = streamResponse.Read(buffer, 0, Length);
        // write the required bytes  
        while (bytesRead > 0)
        {
            _stream.Write(buffer, 0, bytesRead);
            bytesRead = streamResponse.Read(buffer, 0, Length);
        }
        return _stream;
    }

    /// <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, int timeout)
    {
        //初始化对像,并设置请求的URL地址
        //string sUrl = GetUrl(_URL);
        request = (HttpWebRequest)WebRequest.Create(GetUrl(_URL));
        //请求方式Get或者Post
        request.Method = _Method;
        //Accept
        request.Accept = _Accept;
        //ContentType返回类型
        request.ContentType = _ContentType;
        //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
        request.UserAgent = _UserAgent;
        //读取数据时的编码方式
        if (timeout > 0)
        {
            request.Timeout = timeout;
            request.ReadWriteTimeout = timeout;
        }
        encoding = _Encoding;
        CookieContainer cookieCon = new CookieContainer();
        request.CookieContainer = cookieCon;
        System.Net.ServicePointManager.DefaultConnectionLimit = 100;
        request.Referer = _URL.StartsWith("http://") ? _URL : "http://" + _URL;
    }

    /// <summary>
    /// 设置当前访问使用的代理
    /// </summary>
    /// <param name="userName">代理 服务器用户名</param>
    /// <param name="passWord">代理 服务器密码</param>
    /// <param name="ip">代理 服务器地址</param>
    public void SetWebProxy(string userName, string passWord, string ip)
    {
        //设置代理服务器
        WebProxy myProxy = new WebProxy(ip, false);
        //建议连接
        myProxy.Credentials = new NetworkCredential(userName, passWord);
        //给当前请求对象
        request.Proxy = myProxy;
        //设置安全凭证
        request.Credentials = CredentialCache.DefaultNetworkCredentials;
    }

    #endregion

    #region 普通类型
    /// <summary>    
    /// 传入一个正确或不正确的URl,返回正确的URL
    /// </summary>    
    /// <param name="URL">url</param>   
    /// <returns>
    /// </returns>    
    public static string GetUrl(string URL)
    {
        if (!(URL.Contains("http://") || URL.Contains("https://")))
        {
            URL = "http://" + URL;
        }
        return URL;
    }

    /// <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, 0);
        //调用专门读取数据的类
        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, 0);
        //调用专门读取数据的类
        return GetHttpRequestData("");
    }

    public string GetHttpRequestStringByNUll_Get(string URL, Encoding objencoding, int timeout)
    {
        //准备参数
        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, timeout);
        //调用专门读取数据的类
        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,0);
        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, 0);
        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, 0);
        //调用专门读取数据的类
        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, */*,zh-CN", "text/html", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", objencoding, 0);
        //调用专门读取数据的类
        return GetHttpRequestData(strPostdata);
    }

    /// <summary>
    /// 取状态
    /// </summary>
    /// <param name="httpStatusCode"></param>
    /// <returns></returns>
    public string GetStat(HttpStatusCode httpStatusCode, WebHeaderCollection header)
    {
        switch (httpStatusCode)
        {
            case HttpStatusCode.Accepted:
                return "(202)  " + HttpStatusCode.Accepted.ToString();
            case HttpStatusCode.Ambiguous:
                return "(300)  " + HttpStatusCode.Ambiguous.ToString();
            case HttpStatusCode.BadGateway:
                return "(502)  " + HttpStatusCode.BadGateway.ToString();
            case HttpStatusCode.BadRequest:
                return "(400)  " + HttpStatusCode.BadRequest.ToString();
            case HttpStatusCode.Conflict:
                return "(409)  " + HttpStatusCode.Conflict.ToString();
            case HttpStatusCode.Continue:
                return "(100)  " + HttpStatusCode.Continue.ToString();
            case HttpStatusCode.Created:
                return "(201)  " + HttpStatusCode.Created.ToString();
            case HttpStatusCode.ExpectationFailed:
                return "(417)  " + HttpStatusCode.ExpectationFailed.ToString();
            case HttpStatusCode.Forbidden:
                return "(403)  " + HttpStatusCode.Forbidden.ToString();
            case HttpStatusCode.Found:
                return "(302) 页面跳转:" + header["Location"].ToString();
            case HttpStatusCode.GatewayTimeout:
                return "(504)  " + HttpStatusCode.GatewayTimeout.ToString();
            case HttpStatusCode.Gone:
                return "(410)  " + HttpStatusCode.Gone.ToString();
            case HttpStatusCode.HttpVersionNotSupported:
                return "(505)  " + HttpStatusCode.HttpVersionNotSupported.ToString();
            case HttpStatusCode.InternalServerError:
                return "(500)  " + HttpStatusCode.InternalServerError.ToString();
            case HttpStatusCode.LengthRequired:
                return "(411)  " + HttpStatusCode.LengthRequired.ToString();
            case HttpStatusCode.MethodNotAllowed:
                return "(405)  " + HttpStatusCode.MethodNotAllowed.ToString();
            case HttpStatusCode.Moved:
                return "(301) 页面跳转:" + header["Location"].ToString();
            case HttpStatusCode.NoContent:
                return "(204)  " + HttpStatusCode.NoContent.ToString();
            case HttpStatusCode.NonAuthoritativeInformation:
                return "(203)  " + HttpStatusCode.NonAuthoritativeInformation.ToString();
            case HttpStatusCode.NotAcceptable:
                return "(406)  " + HttpStatusCode.NotAcceptable.ToString();
            case HttpStatusCode.NotFound:
                return "(404)  " + HttpStatusCode.NotFound.ToString();
            case HttpStatusCode.NotImplemented:
                return "(501)  " + HttpStatusCode.NotImplemented.ToString();
            case HttpStatusCode.NotModified:
                return "(304)  " + HttpStatusCode.NotModified.ToString();
            case HttpStatusCode.OK:
                return "(200)  " + HttpStatusCode.OK.ToString();
            case HttpStatusCode.PartialContent:
                return "(206)  " + HttpStatusCode.PartialContent.ToString();
            case HttpStatusCode.PaymentRequired:
                return "(402)  " + HttpStatusCode.PaymentRequired.ToString();
            case HttpStatusCode.PreconditionFailed:
                return "(412)  " + HttpStatusCode.PreconditionFailed.ToString();
            case HttpStatusCode.ProxyAuthenticationRequired:
                return "(407)  " + HttpStatusCode.ProxyAuthenticationRequired.ToString();
            case HttpStatusCode.RedirectKeepVerb:
                return "(307)  " + HttpStatusCode.RedirectKeepVerb.ToString();
            case HttpStatusCode.RedirectMethod:
                return "(303)  " + HttpStatusCode.RedirectMethod.ToString();
            case HttpStatusCode.RequestEntityTooLarge:
                return "(413)  " + HttpStatusCode.RequestEntityTooLarge.ToString();
            case HttpStatusCode.RequestTimeout:
                return "(408)  " + HttpStatusCode.RequestTimeout.ToString();
            case HttpStatusCode.RequestUriTooLong:
                return "(414)  " + HttpStatusCode.RequestUriTooLong.ToString();
            case HttpStatusCode.RequestedRangeNotSatisfiable:
                return "(416)  " + HttpStatusCode.RequestedRangeNotSatisfiable.ToString();
            case HttpStatusCode.ResetContent:
                return "(205)  " + HttpStatusCode.ResetContent.ToString();
            case HttpStatusCode.ServiceUnavailable:
                return "(503)  " + HttpStatusCode.ServiceUnavailable.ToString();
            case HttpStatusCode.SwitchingProtocols:
                return "(101)  " + HttpStatusCode.SwitchingProtocols.ToString();
            case HttpStatusCode.Unauthorized:
                return "(401)  " + HttpStatusCode.Unauthorized.ToString();
            case HttpStatusCode.UnsupportedMediaType:
                return "(415)  " + HttpStatusCode.UnsupportedMediaType.ToString();
            case HttpStatusCode.Unused:
                return "(306)  " + HttpStatusCode.Unused.ToString();
            case HttpStatusCode.UseProxy:
                return "(305)  " + HttpStatusCode.UseProxy.ToString();
            default:
                return "无状态";
        }
    }
    #endregion

    #region 不带文件建议Post ....
    /// <summary>
    /// 向指定的URL地址发起一个POST请求,同时可以上传一些数据项。
    /// </summary>
    /// <param name="url">要请求的URL地址</param>
    /// <param name="keyvalues">要上传的数据项</param>
    /// <param name="encoding">发送,接收的字符编码方式</param>
    /// <returns>服务器的返回结果</returns>
    public static string SendHttpRequestPost(string url, Dictionary<string, string> keyvalues, Encoding encoding)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");

        string postData = null;
        // 将数据项转变成 name1=value1&name2=value2 的形式
        if (keyvalues != null && keyvalues.Count > 0)
        {
            postData = string.Join("&",
                    (from kvp in keyvalues
                     let item = kvp.Key + "=" + System.Web.HttpUtility.UrlEncode(kvp.Value)
                     select item
                     ).ToArray()
                 );
        }

        if (encoding == null)
            encoding = Encoding.UTF8;


        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.Referer = "http://tool.chinaz.com";
        request.ContentType = "application/x-www-form-urlencoded; charset=" + encoding.WebName;

        if (postData != null)
        {
            byte[] buffer = encoding.GetBytes(postData);

            Stream stream = request.GetRequestStream();
            stream.Write(buffer, 0, buffer.Length);
            stream.Close();
        }

        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                return reader.ReadToEnd();
            }
        }
    }
    #endregion

}






1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2022-11-29 12:42

© 2014-2021

快速回复 返回顶部 返回列表