Esempio n. 1
0
        /// <summary>
        /// 使用Post方法获取字符串结果
        /// </summary>
        /// <param name="serviceProvider">.NetCore 下的服务器提供程序,如果 .NET Framework 则保留 null</param>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="postStream"></param>
        /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名,或文件内容的Base64编码</param>
        /// <param name="certName">证书唯一名称,如果不需要则保留null</param>
        /// <param name="cer"></param>
        /// <param name="useAjax"></param>
        /// <param name="headerAddition">header附加信息</param>
        /// <param name="timeOut"></param>
        /// <param name="checkValidationResult">验证服务器证书回调自动验证</param>
        /// <param name="contentType"></param>
        /// <param name="refererUrl"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static async Task <string> HttpPostAsync(
            IServiceProvider serviceProvider,
            string url, CookieContainer cookieContainer = null, Stream postStream = null,
            Dictionary <string, string> fileDictionary  = null, string refererUrl = null, Encoding encoding = null,
#if !NET45
            string certName = null,
#else
            X509Certificate2 cer = null,
#endif
            bool useAjax       = false, Dictionary <string, string> headerAddition = null, int timeOut = Config.TIME_OUT, bool checkValidationResult = false,
            string contentType = HttpClientHelper.DEFAULT_CONTENT_TYPE)
        {
            if (cookieContainer == null)
            {
                cookieContainer = new CookieContainer();
            }

            var postStreamIsDefaultNull = postStream == null;

            if (postStreamIsDefaultNull)
            {
                postStream = new MemoryStream();
            }


            //var dt1 = SystemTime.Now;
            //Console.WriteLine($"{System.Threading.Thread.CurrentThread.Name} - START - {dt1:HH:mm:ss.ffff}");

            var senparcResponse = await HttpResponsePostAsync(
                serviceProvider,
                url, cookieContainer, postStream, fileDictionary, refererUrl, encoding,
#if !NET45
                certName,
#else
                cer,
#endif
                useAjax, headerAddition, timeOut, checkValidationResult, contentType).ConfigureAwait(false);;

            var response = senparcResponse.Result;//获取响应信息



            //Console.WriteLine($"{System.Threading.Thread.CurrentThread.Name} - FINISH- {SystemTime.DiffTotalMS(dt1):###,###} ms");


#if NET45
            #region 已经使用方法重用

            /*
             *
             * var request = HttpPost_Common_Net45(url, cookieContainer, postStream, fileDictionary, refererUrl, encoding, cer, useAjax,headerAddition, timeOut, checkValidationResult);
             *
             #region 输入二进制流
             * if (postStream != null && postStream.Length > 0)
             * {
             *  postStream.Position = 0;
             *
             *  //直接写入流
             *  Stream requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false);
             *
             *  byte[] buffer = new byte[1024];
             *  int bytesRead = 0;
             *  while ((bytesRead = await postStream.ReadAsync(buffer, 0, buffer.Length)) != 0).ConfigureAwait(false)
             *  {
             *      await requestStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
             *  }
             *
             *
             *  //debug
             *  //postStream.Seek(0, SeekOrigin.Begin);
             *  //StreamReader sr = new StreamReader(postStream);
             *  //var postStr = await sr.ReadToEndAsync().ConfigureAwait(false);
             *
             *  postStream.Close();//关闭文件访问
             * }
             *
             #endregion
             * HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync()).ConfigureAwait(false);;
             */
            #endregion


            if (cookieContainer != null)
            {
                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
            }

            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
                {
                    string retString = await myStreamReader.ReadToEndAsync().ConfigureAwait(false);

                    return(retString);
                }
            }
#else
            HttpClientHelper.SetResponseCookieContainer(cookieContainer, response);//设置 Cookie

            #region 已经使用方法重用

            /*
             * HttpContent hc;
             * var client = HttpPost_Common_NetCore(url, out hc, cookieContainer, postStream, fileDictionary, refererUrl, encoding, cer, useAjax, timeOut, checkValidationResult);
             *
             * var response = await client.PostAsync(url, hc).ConfigureAwait(false);
             *
             * if (response.Content.Headers.ContentType.CharSet != null &&
             *  response.Content.Headers.ContentType.CharSet.ToLower().Contains("utf8"))
             * {
             *  response.Content.Headers.ContentType.CharSet = "utf-8";
             * }
             *
             *
             * var retString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
             *
             * try
             * {
             *  if (postStreamIsDefaultNull && postStream.Length > 0)
             *  {
             *      postStream.Close();
             *  }
             *
             *  hc.Dispose();//关闭HttpContent(StreamContent)
             * }
             * catch (BaseException ex)
             * {
             * }
             */
            #endregion

            var retString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(retString);
#endif
        }
Esempio n. 2
0
        /// <summary>
        /// 使用Post方法获取HttpWebResponse或HttpResponseMessage对象,本方法独立使用时通常用于测试)
        /// </summary>
        /// <param name="serviceProvider">.NetCore 下的服务器提供程序,如果 .NET Framework 则保留 null</param>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="postStream"></param>
        /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名,或文件内容的Base64编码</param>
        /// <param name="encoding"></param>
        /// <param name="certName">证书唯一名称,如果不需要则保留null</param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax"></param>
        /// <param name="headerAddition">header附加信息</param>
        /// <param name="timeOut"></param>
        /// <param name="checkValidationResult">验证服务器证书回调自动验证</param>
        /// <param name="contentType"></param>
        /// <param name="refererUrl"></param>
        /// <returns></returns>
        public static async Task <SenparcHttpResponse> HttpResponsePostAsync(
            IServiceProvider serviceProvider,
            string url, CookieContainer cookieContainer = null, Stream postStream = null,
            Dictionary <string, string> fileDictionary  = null, string refererUrl = null, Encoding encoding = null,
#if !NET45
            string certName = null,
#else
            X509Certificate2 cer = null,
#endif
            bool useAjax = false, Dictionary <string, string> headerAddition = null, int timeOut = Config.TIME_OUT,
            bool checkValidationResult = false, string contentType           = HttpClientHelper.DEFAULT_CONTENT_TYPE)
        {
            if (cookieContainer == null)
            {
                cookieContainer = new CookieContainer();
            }

            var postStreamIsDefaultNull = postStream == null;

            if (postStreamIsDefaultNull)
            {
                postStream = new MemoryStream();
            }

#if NET45
            var request = HttpPost_Common_Net45(url, cookieContainer, postStream, fileDictionary, refererUrl, encoding, cer, useAjax, headerAddition, timeOut, checkValidationResult, contentType);

            #region 输入二进制流
            if (postStream != null && postStream.Length > 0)
            {
                postStream.Position = 0;

                //直接写入流
                Stream requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false);

                byte[] buffer    = new byte[1024];
                int    bytesRead = 0;
                while ((bytesRead = await postStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
                {
                    await requestStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
                }

                //debug
                //postStream.Seek(0, SeekOrigin.Begin);
                //StreamReader sr = new StreamReader(postStream);
                //var postStr = sr.ReadToEnd();

                postStream.Close();//关闭文件访问
            }
            #endregion

            HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync().ConfigureAwait(false));
            return(new SenparcHttpResponse(response));
#else
            HttpContent hc;
            var         client = HttpPost_Common_NetCore(serviceProvider, url, out hc, cookieContainer, postStream, fileDictionary, refererUrl, encoding, certName, useAjax, headerAddition, timeOut, checkValidationResult, contentType);

            var response = await client.PostAsync(url, hc).ConfigureAwait(false);   //获取响应信息

            HttpClientHelper.SetResponseCookieContainer(cookieContainer, response); //设置 Cookie

            try
            {
                if (postStreamIsDefaultNull && postStream.Length > 0)
                {
                    postStream.Close();
                }

                hc.Dispose();//关闭HttpContent(StreamContent)
            }
            catch (BaseException ex)
            {
            }

            return(new SenparcHttpResponse(response));
#endif
        }
Esempio n. 3
0
        /// <summary>
        /// 使用Post方法获取字符串结果
        /// </summary>
        /// <param name="serviceProvider">.NetCore 下的服务器提供程序,如果 .NET Framework 则保留 null</param>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="postStream"></param>
        /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名,或文件内容的Base64编码</param>
        /// <param name="encoding"></param>
        /// <param name="certName">证书唯一名称,如果不需要则保留null</param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax"></param>
        /// <param name="headerAddition">header 附加信息</param>
        /// <param name="timeOut"></param>
        /// <param name="checkValidationResult">验证服务器证书回调自动验证</param>
        /// <param name="contentType"></param>
        /// <param name="refererUrl"></param>
        /// <returns></returns>
        public static string HttpPost(
            IServiceProvider serviceProvider,
            string url, CookieContainer cookieContainer = null, Stream postStream = null,
            Dictionary <string, string> fileDictionary  = null, string refererUrl = null, Encoding encoding = null,
#if !NET45
            string certName = null,
#else
            X509Certificate2 cer = null,
#endif
            bool useAjax       = false, Dictionary <string, string> headerAddition = null, int timeOut = Config.TIME_OUT, bool checkValidationResult = false,
            string contentType = HttpClientHelper.DEFAULT_CONTENT_TYPE)
        {
            if (cookieContainer == null)
            {
                cookieContainer = new CookieContainer();
            }

            var senparcResponse = HttpResponsePost(
                serviceProvider,
                url, cookieContainer, postStream, fileDictionary, refererUrl, encoding,
#if !NET45
                certName,
#else
                cer,
#endif
                useAjax, headerAddition, timeOut, checkValidationResult, contentType);

            var response = senparcResponse.Result;//获取响应信息


#if NET45
            #region 已经使用方法重用

            /*
             *
             * var request = HttpPost_Common_Net45(url, cookieContainer, postStream, fileDictionary, refererUrl, encoding, cer, useAjax, timeOut, checkValidationResult);
             *
             #region 输入二进制流
             * if (postStream != null)
             * {
             *  postStream.Position = 0;
             *
             *  //直接写入流
             *  Stream requestStream = request.GetRequestStream();
             *
             *  byte[] buffer = new byte[1024];
             *  int bytesRead = 0;
             *  while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
             *  {
             *      requestStream.Write(buffer, 0, bytesRead);
             *  }
             *
             *  //debug
             *  //postStream.Seek(0, SeekOrigin.Begin);
             *  //StreamReader sr = new StreamReader(postStream);
             *  //var postStr = sr.ReadToEnd();
             *
             *  postStream.Close();//关闭文件访问
             * }
             #endregion
             * HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             *
             */

            #endregion

            //HttpWebResponse response = senparcResponse.Result;

            response.Cookies = cookieContainer.GetCookies(response.ResponseUri);

            using (Stream responseStream = response.GetResponseStream() ?? new MemoryStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
                {
                    string retString = myStreamReader.ReadToEnd();
                    return(retString);
                }
            }
#else
            HttpClientHelper.SetResponseCookieContainer(cookieContainer, response);//设置 Cookie

            //var response = senparcResponse.Result;

            if (response.Content.Headers.ContentType != null &&
                response.Content.Headers.ContentType.CharSet != null &&
                response.Content.Headers.ContentType.CharSet.ToLower().Contains("utf8"))
            {
                response.Content.Headers.ContentType.CharSet = "utf-8";
            }

            var retString = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
            return(retString);

            //t1.Wait();
            //return t1.Result;
#endif
        }