MyWebClient.cs 6.0 KB
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;

namespace TSA_V.Common
{
    public class MyWebClient : WebClient
    {
        private int _timeout;

        /// <summary>
        /// 超时时间(毫秒)
        /// </summary>
        public int Timeout
        {
            get
            {
                return _timeout;
            }
            set
            {
                _timeout = value;
            }
        }

        public MyWebClient()
        {
            this._timeout = 60000;
        }

        public MyWebClient(int timeout)
        {
            this._timeout = timeout;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest result = (HttpWebRequest)base.GetWebRequest(address);
            result.Timeout = this._timeout;
            // result.KeepAlive = false;
            result.ServicePoint.Expect100Continue = false;
            return result;
        }
    }
    public class HttpHelper
    {
    
        public static string Post(string url, string paramData, int timeOut = 5000)
        {
            bool IsTimeOut = false;
            return Post(url, paramData, Encoding.UTF8, timeOut, out IsTimeOut);
        }

        private static int isLog = ConfigAppSettings.GetIntValue(Setting_Init.Server_Log_Open);

        public static string  PostJson(string url, Object operation, bool simulate = false)
        {
            try
            {
                if (operation == null)
                {
                    return null;
                } 
                try
                {
                    if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
                    {
                        ServicePointManager.ServerCertificateValidationCallback =
                                       new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
                    }
                    string json = JsonHelper.SerializeObject(operation);
                    var wc = new MyWebClient(5000);
                    if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
                        wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
                    wc.Encoding = Encoding.UTF8;

                    string result = wc.UploadString(url, "POST", json);
                    LogUtil.info("PostJson【" + url + "】发送【"+json+"】返回【"+result+"】");
                    if (!string.IsNullOrEmpty(result))
                    {
                        return result;
                    }
                }
                catch (WebException ex)
                {
                    LogUtil.error("POST [" + url + "] WebException :" + ex.ToString(), 101);
                }
                catch (Exception e)
                {
                    LogUtil.error("POST [" + url + "] ERROR:" + e.ToString(), 101);
                }
            }

            catch (Exception ex)
            {
                LogUtil.error("Post ["+ url + "] 出错:" + ex);
            }
            return null;
        }
        public static string Post(string url, string paramData, Encoding encoding, int timeOut, out bool IsTimeOut)
        {

            if (paramData.Equals(""))
            {
                int index = url.IndexOf("?");
                if (index > 0)
                {
                    paramData = url.Substring(index + 1, url.Length - index - 1);
                    url = url.Substring(0, index);
                }
            }

            IsTimeOut = false;
            if (isLog == 1)
            {
                LogUtil.info("给服务器发送数据【" + url + "】【" + paramData + "】 ");
            }
            string result = "";

            if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                               new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
            }

            try
            {
                var wc = new MyWebClient(timeOut);
                if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
                    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                wc.Encoding = encoding;

                result = wc.UploadString(url, "POST", paramData);
                //LogUtil.info(result);
            }
            catch (WebException ex)
            {
                IsTimeOut = true;
                LogUtil.error("POST [" + url + "] WebException :" + ex.ToString(), 101);
            }
            catch (Exception e)
            {
                LogUtil.error("POST [" + url + "] ERROR:" + e.ToString(), 101);
            }
            if (!result.Contains("null") && result.Length != 0)
            {
                //LogUtil.debug(LOGGER,"receive << " + result);
            }
            if (isLog == 1)
            {
                LogUtil.info("收到服务器数据【" + result + "】");
            }
            return result;
        }

        public static string Get(string url)
        {
            return Get(url, Encoding.UTF8);
        }

        public static string Get(string url, Encoding encoding)
        {
            try
            {
                LogUtil.info("HTTP GET FROM: " + url);
                var wc = new WebClient { Encoding = encoding };
                var readStream = wc.OpenRead(url);
                using (var sr = new StreamReader(readStream, encoding))
                {
                    var result = sr.ReadToEnd();
                    LogUtil.info("receive << " + result);
                    return result;
                }
            }
            catch (Exception e)
            {
                LogUtil.error("HTTP GET ERROR:" + e.Message, 102);
            }
            return "";
        }
    }
}