分享一個自己封裝且一直在維護的依賴.net4.5的http異步組包工具類(支持get,post( 表單 ,json, 包含圖片等文件的流提交) ,cookie管理,自動跳轉,代理IP,https的支持,高並發的配置等等


1.)Nuget安裝:

   搜索 ConfigLab.Comp, 安裝最新版即可.

2.)組包示例.

  2.1)模擬post表單提交並包含普通參數和一個圖片文件(基於HttpFileUploadAssisterAsync這個核心類).

 private async Task<string> GetPostResultForFile_Async()
        {
            string sRspResult = "";
            IWebProxy eWebProxy = this.getWebProxy();//代理IP的設置
            Dictionary<string, string> dictHeader = new Dictionary<string, string>();
            string sUserAgent = this.tbxUserAgent.Text.Trim();
            dictHeader["Accept-Encoding"] = "gzip, deflate";
            dictHeader["Accept-Language"] = "zh-CN,zh;q=0.9";
            dictHeader["Upgrade-Insecure-Requests"] = "1";
            dictHeader["Cache-Control"] = "max-age=0";
            dictHeader["Origin"] = "null";
            Dictionary<string, string> dictImg = new Dictionary<string, string>();//待和參數一起提交的文件信息, key=FullFileName, value=Post內容中的參數Name名的字典
            if (this.tbxImgUrl.Text.IndexOf(":") > -1 && this.tbxImgName.Text.Trim().Length > 0)
            {
                dictImg[this.tbxImgUrl.Text] = this.tbxImgName.Text.Trim();
            }
            else
            {
                if (this.tbxImgName.Text.Trim().Length > 0)
                {
                    dictImg[""] = this.tbxImgName.Text.Trim();
                }
            }
            if (!string.IsNullOrEmpty(this.tbx_Hedaer_Key.Text) && !string.IsNullOrEmpty(this.tbx_Hedaer_Value.Text))
            {
                dictHeader[this.tbx_Hedaer_Key.Text.Trim()] = this.tbx_Hedaer_Value.Text.Trim();
            }
            string sFile_ContentType = "image/jpeg";
            ResponseResult result = new ResponseResult();
            string sUrl = this.tbxUrl.Text.Trim();//輸入的請求地址
            string sPostData = this.tbxPostData.Text.Trim();//同步提交的文本參數 : u=1&a=2這種格式
            string sAccess = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
            //異步模式
            HttpFileUploadAssisterAsync htool = new HttpFileUploadAssisterAsync();//關鍵的類
            Task<ResponseResult> tsk_rrs = htool.SendRequest(new RequestParamsWithFile()
            {
                URL = sUrl,
                Method = "POST",
                Timeout = 10,
                PostData = sPostData,
                DictFileName2PostName = dictImg,//可同時傳遞多個文件
                WriteEnc = Encoding.UTF8,
                ReaderEnc = GetEncoding(),
                WithCookie = this.btnWithCookie.Checked,//是否自動維護cookie
                DictRequestHeaderKeyValues = dictHeader,//自定義包頭
                Accept = sAccess,
                UserAgent = sUserAgent,
                KeepAlive = true,
                EnableExpect100Continue = false,
                File_ContentType = sFile_ContentType,//傳輸的文件類型 
                WebProxy = eWebProxy//代理IP
            });
            await tsk_rrs;
            ResponseResult rrs_rspData = tsk_rrs.Result;
            sRspResult = rrs_rspData.ResponseData;
            return sRspResult;
        }

  2.2)模擬post表單提交並包含普通參數(基於HttpClientAssisterAsync這個核心類).

        private async Task<string>  GetPostResult_Async()
        {
            IWebProxy eProxy = this.getWebProxy();
            HttpClientAssisterAsync htool = new HttpClientAssisterAsync();
            Dictionary<string, string> dictHeader = new Dictionary<string, string>();
            string sUserAgent = this.tbxUserAgent.Text.Trim();
            dictHeader["Content-Type"] = "application/x-www-form-urlencoded";
            dictHeader["Accept-Language"] = "zh-cn";
            if (!string.IsNullOrEmpty(this.tbx_Hedaer_Key.Text) && !string.IsNullOrEmpty(this.tbx_Hedaer_Value.Text))
            {
                dictHeader[this.tbx_Hedaer_Key.Text.Trim()] = this.tbx_Hedaer_Value.Text.Trim();
            }
            Task<ResponseResult>  tsk_result = htool.SendRequest(new RequestParams() {
                URL = this.tbxUrl.Text.Trim(),
                Method = "POST",
                Timeout = 30, //單位秒
                PostData = this.tbxPostData.Text,//表單數據,u=1&p=2這種
                WriteEnc = Encoding.UTF8,
                ReaderEnc = GetEncoding(),
                WithCookie = this.btnWithCookie.Checked,//是否自動管理cookie
                DictRequestHeaderKeyValues = dictHeader, //自定義的包頭信息
                Accept = "*/*",
                UserAgent = sUserAgent,
                KeepAlive = false,
                EnableP3P = false,
                AllowRedrect=false,//是否允許自動跳轉
                 EnableExpect100Continue=true,
                WebProxy = eProxy  //代理IP
            });
            await tsk_result;
            ResponseResult result = tsk_result.Result;
            return string.Format("optime={0}\r\nhttpstatucode={1}\r\nerror={2}\r\nresult={3}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), result.CurrHttpStatuCode, result.ExceptionMsg, result.ResponseData);
        }

   2.3)模擬post提交一個json數據並包含普通參數(基於HttpClientAssisterAsync這個核心類).

        private async Task<string> getResultForPostJson_Async()
        {
            IWebProxy eProxy = this.getWebProxy();
            HttpClientAssisterAsync htool = new HttpClientAssisterAsync();
            Dictionary<string, string> dictHeader = new Dictionary<string, string>();
            string sUserAgent = this.tbxUserAgent.Text.Trim();
            dictHeader["Content-Type"] = "application/json;charset=UTF-8";//重點!!!!
            dictHeader["Accept-Language"] = "zh-cn";
            if (!string.IsNullOrEmpty(this.tbx_Hedaer_Key.Text) && !string.IsNullOrEmpty(this.tbx_Hedaer_Value.Text))
            {
                dictHeader[this.tbx_Hedaer_Key.Text.Trim()] = this.tbx_Hedaer_Value.Text.Trim();
            }
            Task<ResponseResult> tsk_result = htool.SendRequest(new RequestParams()
            {
                URL = this.tbxUrl.Text.Trim(),
                Method = "POST",
                Timeout = 30,
                PostData = this.tbxPostData.Text,//Json數據
                WriteEnc = Encoding.UTF8,
                ReaderEnc = GetEncoding(),
                WithCookie = this.btnWithCookie.Checked,//自動管理cookie
                DictRequestHeaderKeyValues = dictHeader,//自定義包頭
Accept
= "*/*", UserAgent = sUserAgent, KeepAlive = false, EnableP3P = false, AllowRedrect = false, EnableExpect100Continue = true, WebProxy = eProxy }); await tsk_result; ResponseResult result = tsk_result.Result; string sResult = string.Format("optime={0}\r\nhttpstatucode={1}\r\nerrors={2}\r\nresult={3}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), result.CurrHttpStatuCode, result.ExceptionMsg, result.ResponseData); return sResult; }

 2.4)模擬get提交一個數據並包含普通參數(基於HttpClientAssisterAsync這個核心類).

 private async Task<string> GetGetResult_Async()
        {
            IWebProxy eProxy = this.getWebProxy();
            HttpClientAssisterAsync htool = new HttpClientAssisterAsync();
            Dictionary<string, string> dictHeader = new Dictionary<string, string>();
            string sUserAgent = this.tbxUserAgent.Text.Trim();
            if (!string.IsNullOrEmpty(this.tbx_Hedaer_Key.Text) && !string.IsNullOrEmpty(this.tbx_Hedaer_Value.Text))
            {
                dictHeader[this.tbx_Hedaer_Key.Text.Trim()] = this.tbx_Hedaer_Value.Text.Trim();
            }
            Encoding eEncode = this.GetEncoding();
            dictHeader["Accept-Language"] = "zh-CN,zh;q=0.8";
            dictHeader["Cache-Control"] = "max-age=0";
            string sAccess = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            Task<ResponseResult> tsk_rsp = htool.SendRequest(new RequestParams() { 
               URL=this.tbxUrl.Text,
                Method="GET", //在這里設置Get
                Timeout=30,
                  PostData= this.tbxPostData.Text,
                   WriteEnc=Encoding.Default,
                    ReaderEnc=eEncode,
                     WithCookie = this.btnWithCookie.Checked,
                       DictRequestHeaderKeyValues=dictHeader,
                        Accept=sAccess,
                         UserAgent=sUserAgent,
                          KeepAlive=false,
                           EnableP3P=false,
                           AllowRedrect=false,
                            WebProxy=eProxy
            });
            await tsk_rsp;
            ResponseResult result = tsk_rsp.Result;
            return string.Format("optime={0}\r\nhttpstatucode={1}\r\nerror={2}\r\nresult={3}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), result.CurrHttpStatuCode, result.ExceptionMsg, result.ResponseData);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM