示例#1
0
        //private volatile static HttpService _instance = null;
        //private static readonly object lockObj = new object();
        //private HttpService() { }
        //public static HttpService Instance
        //{
        //    get
        //    {
        //        if (_instance == null)
        //        {
        //            lock (lockObj)
        //            {
        //                if (_instance == null)
        //                    _instance = new HttpService();
        //            }
        //        }
        //        return _instance;
        //    }
        //}
        #endregion

        #region Http服务类通用方法
        /// <summary>
        /// 调用HTTP服务的Post方法
        /// </summary>
        /// 作者:赵雪峰 20160520
        /// <param name="url">传入URL</param>
        /// <param name="msg">接口返回的JSON字符串或错误信息</param>
        /// <returns>是否执行成功</returns>
        //public bool PostMethod<Tin, Tout>(string methodName, Tin input, ref Tout output, ref string errMsg)
        //{
        //    string strURL = string.Empty;
        //    string paramData = string.Empty;
        //    try
        //    {
        //        Stopwatch stopWatch = new Stopwatch();
        //        stopWatch.Start();
        //        //DataConverter.SerializeJson(input, ref paramData, ref errMsg);
        //        paramData = FormatInputEntity(input);
        //        strURL = GlobalVariable.ConfigEntity.HttpPrdfix + methodName;
        //        // 创建一个HTTP请求
        //        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
        //        request.Method = "post";
        //        request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
        //        byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
        //        request.ContentLength = byteArray.Length;
        //         Stream newStream = request.GetRequestStream();
        //        newStream.Write(byteArray, 0, byteArray.Length);//写入参数
        //        newStream.Close();

        //        System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
        //        System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
        //        string responseText = myreader.ReadToEnd();
        //        myreader.Close();
        //        response.Close();
        //        //msg = responseText;
        //        bool getReturnInfo = DataConverter.DeserializeJson<Tout>(responseText, ref output, ref errMsg);
        //        if (!getReturnInfo)
        //        {
        //            return false;
        //        }
        //        stopWatch.Stop();
        //        if (methodName != "/antuser/user.listContacts.do")//获取组织结构数据量太大, 不在这里记日志
        //        {
        //            LogHelper.WriteDebug(string.Format("[HTTPService.PostMethod({0}毫秒)]:{1}", stopWatch.Elapsed.TotalMilliseconds, strURL + "?"+paramData+ Environment.NewLine + responseText));
        //        }
        //        string errCodeStr = string.Empty;
        //        if (DataConverter.GetValueByJsonKey("errorCode", responseText, ref errCodeStr, ref errMsg)
        //            && errCodeStr == "1004"
        //            && TokenErrorEvent != null)//获取errorCode
        //        {
        //            if (TokenErrorEvent != null) TokenErrorEvent(null, null);

        //        }
        //        return true;
        //    }
        //    catch (WebException e)
        //    {

        //        string status = null;
        //        HttpWebResponse response = (HttpWebResponse)e.Response;
        //        System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
        //        string responseText = myreader.ReadToEnd();
        //        myreader.Close();
        //        response.Close();
        //        if (response.StatusCode == HttpStatusCode.NotFound)
        //            status = "404";
        //        if (response.StatusCode == HttpStatusCode.InternalServerError)
        //            status = "500";
        //        if (response.StatusCode == HttpStatusCode.BadGateway)
        //            status = "502";

        //        errMsg = "访问后台服务失败";
        //        if (methodName == "/antuser/user.login.do")//登录接口,日志不记录密码
        //        {
        //            LogHelper.WriteError("[HTTPService.PostMethod]:" + GlobalVariable.ConfigEntity.HttpPrdfix + methodName + Environment.NewLine + e.Message + "," + e.StackTrace);
        //        }
        //        else
        //        {
        //            LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + Environment.NewLine + e.Message + "," + e.StackTrace);
        //        }
        //        return false;
        //    }
        //}
        ///// <summary>
        /////
        ///// </summary>
        ///// <typeparam name="Tin"></typeparam>
        ///// <typeparam name="Tout"></typeparam>
        ///// <param name="methodName"></param>
        ///// <param name="input"></param>
        ///// <param name="output"></param>
        ///// <param name="errMsg"></param>
        ///// <returns></returns>
        //public bool GetMethod<Tin, Tout>(string methodName, Tin input, ref Tout output, ref string errMsg)
        //{
        //    string strURL = string.Empty;
        //    string paramData = string.Empty;
        //    try
        //    {
        //        Stopwatch stopWatch = new Stopwatch();
        //        stopWatch.Start();
        //        //DataConverter.SerializeJson(input, ref paramData, ref errMsg);
        //        paramData = FormatInputEntity(input);
        //        strURL = GlobalVariable.ConfigEntity.HttpPrdfix + methodName;
        //        // 创建一个HTTP请求
        //        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(strURL+"?"+ paramData);
        //        request.Method = "GET";
        //        request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

        //        System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
        //        System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
        //        string responseText = myreader.ReadToEnd();
        //        myreader.Close();
        //        response.Close();
        //        bool getReturnInfo = DataConverter.DeserializeJson<Tout>(responseText, ref output, ref errMsg);
        //        if (!getReturnInfo)
        //        {
        //            return false;
        //        }
        //        stopWatch.Stop();
        //        if (methodName != "/antuser/user.listContacts.do")//获取组织结构数据量太大, 不在这里记日志
        //        {
        //            LogHelper.WriteDebug(string.Format("[HTTPService.PostMethod({0}毫秒)]:{1}", stopWatch.Elapsed.TotalMilliseconds, strURL + "?" + paramData + Environment.NewLine + responseText));
        //        }
        //        string errCodeStr = string.Empty;
        //        if (DataConverter.GetValueByJsonKey("errorCode", responseText, ref errCodeStr, ref errMsg)
        //            && errCodeStr == "1004"
        //            && TokenErrorEvent != null)//获取errorCode
        //        {
        //            if (TokenErrorEvent != null) TokenErrorEvent(null, null);

        //        }
        //        return true;
        //    }
        //    catch (Exception e)
        //    {
        //        errMsg = "访问后台服务失败";
        //        if (methodName == "/antuser/user.login.do")//登录接口,日志不记录密码
        //        {
        //            LogHelper.WriteError("[HTTPService.PostMethod]:" + GlobalVariable.ConfigEntity.HttpPrdfix + methodName + Environment.NewLine + e.Message + "," + e.StackTrace);
        //        }
        //        else
        //        {
        //            LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + Environment.NewLine + e.Message + "," + e.StackTrace);
        //        }
        //        return false;
        //    }
        //}

        /// <summary>
        /// HTTP请求统一入口
        /// </summary>
        /// <typeparam name="Tin"></typeparam>
        /// <typeparam name="Tout"></typeparam>
        /// <param name="methodName"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="errMsg"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public bool HttpCommonMethod <Tin, Tout>(string methodName, RequestMethod requestType, Tin input, ref Tout output, ref string errMsg)
        {
            string strURL    = string.Empty;
            string paramData = string.Empty;

            try
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                paramData = FormatInputEntity(input);
                strURL    = GlobalVariable.ConfigEntity.HttpPrdfix + methodName;

                System.Net.HttpWebRequest request = null;
                if (requestType.ToString().ToLower() == "post")
                {
                    // 创建一个HTTP请求
                    request             = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                    request.Method      = requestType.ToString();
                    request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
                    request.ContentLength = byteArray.Length;
                    Stream newStream = request.GetRequestStream();
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    newStream.Close();
                }
                else
                {
                    // 创建一个HTTP请求
                    request             = (System.Net.HttpWebRequest)WebRequest.Create(strURL + "?" + paramData);
                    request.Method      = requestType.ToString();
                    request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                }

                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader     myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string responseText = myreader.ReadToEnd();
                myreader.Close();
                response.Close();
                //msg = responseText;
                bool getReturnInfo = DataConverter.DeserializeJson <Tout>(responseText, ref output, ref errMsg);
                if (!getReturnInfo)
                {
                    return(false);
                }
                stopWatch.Stop();
                if (methodName != "/antuser/user.listContacts.do")//获取组织结构数据量太大, 不在这里记日志
                {
                    LogHelper.WriteDebug(string.Format("[HTTPService.PostMethod({0}毫秒)]:{1}", stopWatch.Elapsed.TotalMilliseconds, strURL + "?" + paramData + Environment.NewLine + responseText));
                }
                string errCodeStr = string.Empty;
                if (DataConverter.GetValueByJsonKey("errorCode", responseText, ref errCodeStr, ref errMsg) &&
                    errCodeStr == "1004" &&
                    TokenErrorEvent != null)   //获取errorCode
                {
                    if (TokenErrorEvent != null)
                    {
                        TokenErrorEvent(null, null);
                    }
                }
                return(true);
            }
            catch (WebException e)
            {
                try
                {
                    HttpWebResponse        response = (HttpWebResponse)e.Response;
                    System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(),
                                                                                 Encoding.UTF8);
                    string responseText = myreader.ReadToEnd();
                    myreader.Close();
                    response.Close();
                    string errCodeStr = string.Empty;
                    if (DataConverter.GetValueByJsonKey("errorCode", responseText, ref errCodeStr, ref errMsg) &&
                        errCodeStr == "1004" &&
                        TokenErrorEvent != null)    //获取errorCode
                    {
                        if (TokenErrorEvent != null)
                        {
                            TokenErrorEvent(null, null);
                        }
                    }
                    errMsg = "访问后台服务失败";
                    if (methodName == "/antuser/user.login.do") //登录接口,日志不记录密码
                    {
                        LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + "?" + paramData +
                                             Environment.NewLine + e.Message + "," + responseText);
                    }
                    else
                    {
                        LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + Environment.NewLine + e.Message +
                                             "," + responseText);
                    }
                }
                catch
                {
                    errMsg = "访问后台服务失败";
                    if (methodName == "/antuser/user.login.do")//登录接口,日志不记录密码
                    {
                        LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + "?" + paramData + Environment.NewLine + e.Message);
                    }
                    else
                    {
                        LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + Environment.NewLine + e.Message + e.StackTrace);
                    }
                }
                return(false);
            }
            catch (Exception e)
            {
                errMsg = "访问后台服务失败";
                if (methodName == "/antuser/user.login.do")//登录接口,日志不记录密码
                {
                    LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + "?" + paramData + Environment.NewLine + e.Message);
                }
                else
                {
                    LogHelper.WriteError("[HTTPService.PostMethod]:" + strURL + Environment.NewLine + e.Message + e.StackTrace);
                }
                return(false);
            }
        }