程序后端调用post请求。

   /// <summary>
    /// 调用Web API
    /// </summary>
    public class InvokeMVCWebAPI
    {
        /// <summary>
        ///     如果ErrorCode不是成功直接抛出异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="soaLoginRequest"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static SOAResponse<T> InvokeMvcWebApi<T>(
            HttpMethod method,
            string url,
            SOALoginRequest soaLoginRequest = null,
            object obj = null, int Timeout_seconds = 600)
        {
            if (soaLoginRequest == null)
            {
                soaLoginRequest = new SOALoginRequest
                {
                    UserCookie =
                        LoginHelper.GetLoginCookieValue,
                    AppId = UtilVar.AppId,
                    AppSecrect = UtilVar.AppSecret
                };
            }
            if (string.IsNullOrWhiteSpace(soaLoginRequest.UserCookie))
                soaLoginRequest.UserCookie = LoginHelper.GetLoginCookieValue;

            return HttpWebRequestGetPost<T>(method, url, soaLoginRequest, obj, Timeout_seconds: Timeout_seconds);

        }

        //private static object async_object = new object();


        /// <summary>
        /// 同步方法 超时20分钟
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="soaLoginRequest"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static SOAResponse<T> HttpWebRequestGetPost<T>(HttpMethod method,
            string url,
            SOALoginRequest soaLoginRequest,
            object obj = null, int Timeout_seconds = 600)
        {
            string jsonObj = "";
            if (obj != null)
                jsonObj = JSON.SerializeAllField(obj);


            var returnObj = new SOAResponse<T>
            {
                Body = default(T)
            };
            var req = (HttpWebRequest)HttpWebRequest.Create(url);
            var encoding = Encoding.UTF8;
            req.Accept = "application/json";



            req.Headers.Add("X_31HuiYi_LoginCookie", soaLoginRequest.UserCookie);
            //string appStr = LoginHelper.SetAppRequest(method, UtilVar.UrlDecode(url), soaLoginRequest);
            string appStr = LoginHelper.SetAppRequest(method, url, soaLoginRequest);
            req.Headers.Add("X_31HuiYi_AppAuth", appStr);
            //设置没有缓存
            req.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            req.Timeout = Timeout_seconds * 1000;
            string responseData = String.Empty;
            req.Method = method.ToString();

            req.ContentType = "application/json";


            byte[] bs = null;
            if (req.Method == "POST" || req.Method == "PUT")
            {
                if (obj != null)
                {
                    bs = encoding.GetBytes(jsonObj);
                    req.ContentLength = bs.Length;
                }
                else
                    req.ContentLength = 0;

                using (Stream reqStream = req.GetRequestStream())
                {
                    if (obj != null)
                        reqStream.Write(bs, 0, bs.Length);
                    reqStream.Close();
                }
            }


            try
            {
                using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                    {
                        responseData = reader.ReadToEnd().ToString();
                        returnObj = JSON.Deserialize<SOAResponse<T>>(responseData);
                        if (response.IsFromCache)
                            throw new Exception("不能进行缓存--scofi");
                        Console.WriteLine("成功");
                        return returnObj;
                    }
                }
            }
            catch (Exception e)
            {
                returnObj.Body = default(T);

                returnObj.Code = ErrorCode.未知错误;
                returnObj.AddDefaultMessage("发生未捕捉的异常:" + e.ToString() + " source=" + e.Source + " e.InnerException=" + (e.InnerException == null ? "" : e.InnerException.ToString()));
                Console.WriteLine("发生未捕捉的异常:" + e.ToString() + " source=" + e.Source + " e.InnerException=" + (e.InnerException == null ? "" : e.InnerException.ToString()));

                //    string msg = "发生未捕捉的异常:" + e.ToString() + " source=" + e.Source + " e.InnerException=" + (e.InnerException == null ? "" : e.InnerException.ToString());

                //if (string.IsNullOrWhiteSpace(e.Message) == false && e.Message.Contains("(404)"))
                //{
                //    LogHelper.Log(LogType.Error, 123, 123, "req.Method= " + req.Method.ToString() + ",   url=" + url + "             ,msg=" + msg, tags: new List<string>() { "404路由错误" });
                //}
                //else if (string.IsNullOrWhiteSpace(e.Message) == false && e.Message.Contains("(405)"))
                //{
                //    LogHelper.Log(LogType.Error, 123, 123, "req.Method= " + req.Method.ToString() + ",   url=" + url + "             ,msg=" + msg, tags: new List<string>() { "405路由method错误" });            
                //}//远程服务器返回错误: (405) 不允许的方法。


                //mongoDB 查询语法:{"Tags":{"$in":["404路由错误","405路由method错误"]}}
                return returnObj;
            }

        }

      

        /// <summary>
        ///     会设置AppAuth
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="soaLoginRequest"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private static HttpRequestMessage GetReqeustMessage(HttpMethod method, string url,
            SOALoginRequest soaLoginRequest, JsonHttpContent content = null)
        {
            var uri = new Uri(url);
            var msg = new HttpRequestMessage(method, uri);
            if (content != null) msg.Content = content;
            msg.Headers.Add("X_31HuiYi_AppAuth", LoginHelper.SetAppRequest(method, url, soaLoginRequest));

            return msg;
        }


       
    }

SOAResponse

 

 

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace HYService.Util
{
    /// <summary>
    /// SOA 响应
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable, JsonObject(MemberSerialization.OptOut)]
    public class SOAResponse<T>
    {
        /// <summary>
        /// 
        /// </summary>
        public SOAResponse()
        {
            Code = ErrorCode.成功;
            Message = new Dictionary<string, string>();
        }

        /// <summary>
        /// 成功,失败通用的一个错误提示信息; 只能添加一次(否则字典抛出异常)
        /// </summary>
        /// <param name="defaultMessage"></param>
        public void AddDefaultMessage(string defaultMessage)
        {
            if (Message.ContainsKey("defaultMessage") == false)
            {
                Message.Add("defaultMessage", defaultMessage);
            }
            else
                Message["defaultMessage"] = Message["defaultMessage"] + "; " + defaultMessage; ;
        }

        /// <summary>
        /// 获取设置默认值
        /// </summary>
        /// <returns></returns>
        public string DefaultMessage
        {
            get
            {
                if (Message.ContainsKey("defaultMessage"))
                {
                    return Message["defaultMessage"];
                }
                return string.Empty;
            }

            set
            {
                if (Message.ContainsKey("defaultMessage") == false)
                    Message.Add("defaultMessage", value);
                else
                    Message["defaultMessage"] = value;
            }
        }

        /// <summary>
        /// 添加消息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool AddMessage(string key, string message)
        {
            if (Message.ContainsKey(key) == false)
            {
                Message.Add(key, message);
                return true;
            }
            else
            {
                Message[key] += "," + message;
            }
            return false;
        }

        /// <summary>
        /// 0 表示成功, (默认成功)  负数表示程序抛出异常;          正数表示业务规则不符合要求
        /// </summary>
        public ErrorCode Code { get; set; }

        /// <summary>
        /// 失败(成功)的描述信息; 添加时候请调用 AddMessage;而不是直接操作字典
        /// </summary>
        public Dictionary<string, string> Message { get; set; }



        /// <summary>
        /// 生成成功响应
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public static SOAResponse<T> MakeSucc(T body)
        {
            return new SOAResponse<T>
            {
                Code = ErrorCode.成功,
                Body = body
            };
        }

        /// <summary>
        /// 创建失败
        /// </summary>
        /// <param name="err"></param>
        /// <returns></returns>
        [Obsolete]
        public static SOAResponse<T> MakeFailed(ErrorCode err = ErrorCode.未知错误)
        {
            return CreateFailed("未知错误", err);
        }

        /// <summary>
        /// 设置为失败
        /// </summary>
        /// <param name="defaultMessage"></param>
        /// <param name="errorCode"></param>
        public SOAResponse<T> Fail(string defaultMessage = "失败!", ErrorCode errorCode = ErrorCode.未知错误)
        {
            Code = errorCode;
            AddDefaultMessage(defaultMessage);
            return this;
        }

        /// <summary>
        /// 创建一个失败
        /// </summary>
        /// <param name="defaultMessage"></param>
        /// <param name="errorCode"></param>
        /// <returns></returns>
        public static SOAResponse<T> CreateFailed(string defaultMessage = "失败!", ErrorCode errorCode = ErrorCode.未知错误)
        {
            var response = new SOAResponse<T>();
            response.Fail(defaultMessage, errorCode);
            return response;
        }

        /// <summary>
        /// 是否成功
        /// </summary>
        /// <returns></returns>
        public bool IsOk()
        {
            return this.Code == ErrorCode.成功;
        }



        /// <summary>
        /// 返回的对象(主要是让 JSON 序列化 返回的参数在后面)
        /// </summary>  
        public T Body;
    }

    /// <summary>
    /// 
    /// </summary>
    public enum ErrorCode
    {
        /// <summary>
        /// 程序异常
        /// </summary>
        程序异常 = -2,
        /// <summary>
        /// 
        /// </summary>
        授权失败 = -1,

        /// <summary>
        /// 成功
        /// </summary>
        成功 = 0,

        /// <summary>
        /// 
        /// </summary>
        未知错误 = 1,
 
    }

  直接调用

 

     if (string.IsNullOrWhiteSpace(info.JsonPOSTData) == false)
                    {
                        dynamic d = JSON.Deserialize<dynamic>(info.JsonPOSTData);
                        result = InvokeMVCWebAPI.InvokeMvcWebApi<bool>(System.Net.Http.HttpMethod.Post, info.PostURL, null, d, timeoutsecond);
                    }
                    else
                    {
                        result = InvokeMVCWebAPI.InvokeMvcWebApi<bool>(System.Net.Http.HttpMethod.Post, info.PostURL, Timeout_seconds: timeoutsecond);
                    }
                    info.ErrorMessages.Add(JSON.SerializeAllField(result));

  

  

 

posted @ 2016-07-01 11:39  相忘江湖何处去  阅读(546)  评论(0编辑  收藏  举报