Esempio n. 1
0
        /// <summary>
        /// 执行带body体的POST请求。
        /// </summary>
        /// <param name="url">请求地址,含URL参数</param>
        /// <param name="body">请求body体字节流</param>
        /// <param name="contentType">body内容类型</param>
        /// <param name="headerParams">请求头部参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPostJson(BrowserPara browserPara)
        {
            LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString());
            string         url = browserPara.Uri;
            HttpWebRequest req = GetWebRequest(browserPara, "POST");

            req.ContentType = browserPara.ContentType;
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线

            req.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            System.IO.Stream reqStream         = req.GetRequestStream();
            byte[]           itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[]           endBoundaryBytes  = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            reqStream.Close();

            HttpWebResponse rsp                = (HttpWebResponse)req.GetResponse();
            Encoding        encoding           = GetResponseEncoding(rsp);
            string          responseFromServer = GetResponseAsString(req, rsp, encoding);

            LogAgent.Info(req.CookieContainer.GetCookieHeader(new Uri(browserPara.Uri)));
            LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, responseFromServer);
            return(responseFromServer);
        }
Esempio n. 2
0
        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="textParams">请求文本参数</param>
        /// <param name="headerParams">请求头部参数</param>
        /// <returns>HTTP响应</returns>
        public string DoGet(BrowserPara browserPara)
        {
            LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString());
            HttpWebRequest req = GetWebRequest(browserPara, "GET");

            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            HttpWebResponse rsp                = (HttpWebResponse)req.GetResponse();
            Encoding        encoding           = GetResponseEncoding(rsp);
            string          responseFromServer = GetResponseAsString(req, rsp, encoding);

            LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, responseFromServer);
            return(responseFromServer);
        }
Esempio n. 3
0
        public static string HttpGet(BrowserPara browserPara)
        {
            try
            {
                LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString());
                HttpWebRequest request = WebRequest.Create(browserPara.Uri) as HttpWebRequest;
                //每次请求绕过代理,解决第一次调用慢的问题
                request.Proxy = null;
                //使用已经保存的cookies
                //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
                ServicePoint currentServicePoint = request.ServicePoint;
                currentServicePoint.ConnectionLimit = 1000;
                if (browserPara.Headers != null)
                {
                    foreach (var header in browserPara.Headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }
                string cookie = GetCookie();
                if (!String.IsNullOrEmpty(cookie))
                {
                    request.Headers.Add("Cookie", cookie);
                }

                string str;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        str = reader.ReadToEnd();
                    }
                    ProcessResponseCookies(request, response);
                    request.Abort();
                    request = null;
                }
                LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, str);
                return(str);
            }
            catch (Exception ex)
            {
                LogAgent.Error(ex.ToString());
            }
            return(String.Empty);
        }
Esempio n. 4
0
        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="textParams">请求文本参数</param>
        /// <param name="headerParams">请求头部参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(BrowserPara browserPara)
        {
            LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString());
            string         url = browserPara.Uri;
            HttpWebRequest req = GetWebRequest(browserPara, "Post");

            req.ContentType = browserPara.ContentType;
            byte[]           postData  = Encoding.UTF8.GetBytes(browserPara.PostData);
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp                = (HttpWebResponse)req.GetResponse();
            Encoding        encoding           = GetResponseEncoding(rsp);
            string          responseFromServer = GetResponseAsString(req, rsp, encoding);

            LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, responseFromServer);
            return(responseFromServer);
        }
Esempio n. 5
0
        private HttpWebRequest GetWebRequest(BrowserPara browserPara, string method)
        {
            string url = browserPara.Uri;
            IDictionary <string, string> headerParams = browserPara.Headers;
            HttpWebRequest req = null;

            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                if (this._ignoreSSLCheck)
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(TrustAllValidationCallback);
                }
                req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                req = (HttpWebRequest)WebRequest.Create(url);
            }


            if (headerParams != null && headerParams.Count > 0)
            {
                foreach (string key in headerParams.Keys)
                {
                    req.Headers.Add(key, headerParams[key]);
                }
            }

            req.CookieContainer = HttpHelper.Example.cookies;

            req.Proxy = null;
            req.ServicePoint.Expect100Continue = false;
            req.Method           = method;
            req.KeepAlive        = true;
            req.UserAgent        = browserPara.UserAgent;
            req.Accept           = browserPara.Accept;
            req.Timeout          = browserPara.Timeout;
            req.ReadWriteTimeout = browserPara.ReadWriteTimeout;
            return(req);
        }
Esempio n. 6
0
 public static string HttpPost(BrowserPara browserPara)
 {
     try
     {
         LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString());
         HttpWebRequest request = WebRequest.Create(browserPara.Uri) as HttpWebRequest;
         //将发送数据转换为二进制格式
         byte[] byteArray = Encoding.UTF8.GetBytes(browserPara.PostData);
         //要POST的数据大于1024字节的时候, 浏览器并不会直接就发起POST请求, 而是会分为俩步:
         //1. 发送一个请求, 包含一个Expect:100-continue, 询问Server使用愿意接受数据
         //2. 接收到Server返回的100-continue应答以后, 才把数据POST给Server
         //直接关闭第一步验证
         request.ServicePoint.Expect100Continue = false;
         //是否使用Nagle:不使用,提高效率
         request.ServicePoint.UseNagleAlgorithm = false;
         //设置最大连接数
         request.ServicePoint.ConnectionLimit = 65500;
         //指定压缩方法
         //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
         //使用已经保存的cookies
         request.KeepAlive     = false;
         request.ContentType   = browserPara.ContentType;
         request.Method        = HttpMethod.Post.Method.ToString();
         request.Timeout       = browserPara.Timeout;
         request.ContentLength = byteArray.Length;
         //关闭缓存
         request.AllowWriteStreamBuffering = false;
         //每次请求绕过代理,解决第一次调用慢的问题
         request.Proxy = null;
         //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
         ServicePoint currentServicePoint = request.ServicePoint;
         if (browserPara.Headers != null)
         {
             foreach (var header in browserPara.Headers)
             {
                 request.Headers.Add(header.Key, header.Value);
             }
         }
         string cookie = GetCookie();
         if (!String.IsNullOrEmpty(cookie))
         {
             request.Headers.Add("Cookie", cookie);
         }
         string responseFromServer = String.Empty;
         using (Stream dataStream = request.GetRequestStream())
         {
             dataStream.Write(byteArray, 0, byteArray.Length);
             using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
             {
                 //获取服务器返回的数据流
                 using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                 {
                     responseFromServer = reader.ReadToEnd();
                 }
                 ProcessResponseCookies(request, response);
             }
             request.Abort();
         }
         LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, responseFromServer);
         return(responseFromServer);
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return(String.Empty);
 }