コード例 #1
0
        public byte[] GetParams(HttpWebRequest request, HttpPackage package)
        {
            request.Method = "POST";//以POST方式传递数据
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            //request.Headers.Add(Constants.HTTP_COMM_PROTOCOL, Constants.HTTP_VERSION);
            request.Headers.Add(Constants.HTTP_COMM_PROTOCOL, "");

            StringBuilder sb = new StringBuilder();

            IDictionary<string, string> param = JsonUtil.toParameters(package.GetParams());

            foreach (string key in param.Keys)
            {
                sb.Append(key);
                sb.Append('=');
                sb.Append(param[key]);
                sb.Append('&');
            }
            return Encoding.UTF8.GetBytes(sb.ToString());
            //return Encoding.Default.GetChars(Encoding.Default.GetBytes(sb.ToString()));
            //return Encoding.UTF8.GetString(bs, 0, bs.Length);
            //return Constants.HTTP_JSON_PARAM+"=" + HttpUtility.UrlEncode(b64s) +
            //    "&" + Constants.HTTP_REQUEST_CODING+ "=" + Encoding.Default.BodyName +
            //    //"&__version__=0.1"+
            //    "&" + Constants.HTTP_RESULT + "=json";
        }
コード例 #2
0
        public byte[] GetParams(HttpWebRequest request, HttpPackage package)
        {
            request.Method = "POST";//以POST方式传递数据
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add(Constants.HTTP_COMM_PROTOCOL, Constants.HTTP_VERSION);

            StringBuilder sb = new StringBuilder();
            sb.Append('{');
            sb.Append("\"location\":");
            sb.Append("\"" + package.location + "\",");
            sb.Append("\"timestamp\":");
            sb.Append(Utils.Timestamp);
            sb.Append(",\"sequeueid\":");
            sb.Append(Utils.Sequeue);

            //增加版本信息
            sb.Append(",\"version\":{\"major\":");
            sb.Append(package.Version.Major);
            sb.Append(",\"minor\":");
            sb.Append(package.Version.Minor);
            sb.Append("}");

            //增加参数信息
            sb.Append(",\"data\":");
            IDictionary<string, object> dict = package.GetParams();
            //Lin.Core.Web.Json.DataContractJsonSerializer dc = new Lin.Core.Web.Json.DataContractJsonSerializer(typeof(Dictionary<string, object>));
            ////String jsonString = "{}";
            //MemoryStream ms = new MemoryStream();
            //dc.WriteObject(ms, dict);
            //byte[] tmp = ms.ToArray();
            //sb.Append(Encoding.UTF8.GetString(tmp, 0, tmp.Length));

                sb.Append(JsonUtil.Serialize(dict));

            //sb.Append("{\"data\":\"测试中文\"}");

            sb.Append("}");

            string b64s = System.Convert.ToBase64String(Encoding.Default.GetBytes(sb.ToString()));
            //Console.WriteLine("value:" + sb.ToString());
            //Console.WriteLine("b64s:" + b64s);
            //Console.WriteLine("coding:" + Encoding.Default.EncodingName);
            string r = Constants.HTTP_JSON_PARAM+"=" + HttpUtility.UrlEncode(b64s) +
                "&" + Constants.HTTP_REQUEST_CODING+ "=" + Encoding.Default.BodyName +
                //"&__version__=0.1"+
                "&" + Constants.HTTP_RESULT + "=json";
            return Encoding.ASCII.GetBytes(r);
        }
コード例 #3
0
ファイル: BaseTest.cs プロジェクト: wangjianglin/dotnet-core
 /// <summary>
 /// 实现对HTTP的同步调用,使得对返回结果的诊断 是 和测试线程在同一线程中
 /// 
 /// 这样在诊断出错,或产生异常时才能捕获测试结果
 /// </summary>
 /// <param name="package"></param>
 /// <param name="result"></param>
 /// <param name="fault"></param>
 /// <param name="code">当出现错误时,错误码不为code时,测试失败,为null则不处理</param>
 public void Request(HttpPackage package, Action<object, IList<Error>> result = null, Action<Error> fault = null,long? code = 0)
 {
     //AutoResetEvent are = new AutoResetEvent(false);
     bool flag = false;
     object tmpResultObject = null;
     IList<Error> tmpWarning = null;
     Error tmpError = null;
     HttpCommunicate.Request(package, (resultObject, warning) =>
     {
         tmpResultObject = resultObject;
         tmpWarning = warning;
         flag = true;
         //are.Set();
     }, error =>
     {
         tmpError = error;
         //are.Set();
     }).WaitForEnd();
     //are.WaitOne();
     if (flag == true)
     {
         if (result != null)
         {
             result(tmpResultObject, tmpWarning);
         }
     }
     else
     {
         if (code != null)
         {
             //Console.WriteLine("error:-0x{0:X}_{1:X4}", Math.Abs((long)(tmpError.code / 65536)), Math.Abs(tmpError.code) % 65536);
             //Console.WriteLine("error message:" + tmpError.message);
             //Console.WriteLine("error cause:" + tmpError.cause);
             //Console.WriteLine("errot stack trace:" + tmpError.stackTrace);
             //Console.WriteLine("data:" + tmpError.data);
             //if (tmpError.code != code)
             //{
             //    Console.WriteLine("server build:" + VersionInfo.build);
             //}
             //Assert.IsTrue(tmpError.code == code);
         }
         if (fault != null)
         {
             fault(tmpError);
         }
     }
 }
コード例 #4
0
        public void Response(HttpPackage package, byte[] bs,Action<Object,IList<Error>> result, Action<Error> fault)
        {
            string resp = null;
            try
            {
                //resp = Encoding.ASCII.GetDecoder().
                //resp = HttpUtility.UrlDecode(resp);

                //resultString new String(System.Convert.FromBase64String(resultString));
                //Stream stream = new MemoryStream(System.Convert.FromBase64String(resp));
                Stream stream = new MemoryStream(bs);
                resp = new StreamReader(stream, Encoding.UTF8, true).ReadToEnd();
            }
            catch (System.ArgumentNullException e)
            {
                if (fault != null)
                {
                    Error error = new Error(0x2000009, "没有返回数据!", resp, e.StackTrace);
                    fault(error);
                    return;
                }
            }
            catch (System.ArgumentException e)
            {
                if (fault != null)
                {
                    Error error = new Error(0x200000a, "返回数据编码错误!", resp, e.StackTrace);
                    fault(error);
                    return;
                }
            }
            catch (System.FormatException e)
            {
                if (fault != null)
                {
                    Error error = new Error(0x200000b, "返回数据格式错误!", resp, e.StackTrace);
                    fault(error);
                    return;
                }
            }
              ProcessResultData(package,resp,result,fault);
        }
コード例 #5
0
        private void ProcessResultData(HttpPackage package,String resultString,Action<Object,IList<Error>> Result, Action<Error> Fault)
        {
            //对返回数据进行处理
            //System.Runtime.Serialization.Json.DataContractJsonSerializer dc = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ResultData));
            //Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(resultString));
            //Console.WriteLine(resultString);
            //object data = dc.ReadObject(stream);
            if (resultString == null || resultString == "")
            {
                Error error = new Error(0x2000005, "无返回数据!", resultString);
                Fault(error);
                return;
            }
            JsonValue jsonValue = null;
            ResultData tmp = null;
            try
            {
                jsonValue = JsonUtil.Deserialize(resultString) as JsonValue;
                tmp = JsonUtil.Deserialize<ResultData>(jsonValue);
            }
            catch (Exception e)
            {
                Error error = new Error(0x2000006, "服务器返回数据格式错误!", resultString, e.StackTrace);
                Fault(error);
                return;
                //this.Fault(resultString);
            }
            if (tmp != null && tmp.code < 0)
            {
                //返回数据有误,抛出异常
                //MessageBox.Show("系统异常:\r\n错误代码:0x" + tmp.code.ToString("X") + "\r\n错误消息:" + tmp.message);
                //tmp.result = null;
                //Console.WriteLine("error:\n" + resultString);
                //Error error = new Error(tmp.error, tmp.message, tmp.cause);
                ValidationErrorData errorData = JsonUtil.Deserialize<ValidationErrorData>(jsonValue["result"]);
                Error error = tmp.CopyProperty<Error>();
                error.data = errorData;
                Fault(error);
                return;
            }
            JsonValue tmpJv = null;
            try
            {
                tmpJv = jsonValue["result"];
            }
            catch (System.Exception e)
            {
                Error error = new Error(0x2000007, "无法得到返回结果!", resultString, e.StackTrace);
                Fault(error);
                return;
            }
            //if (tmpJv != null)
            //{
            //Console.WriteLine("result:" + resultString);
            //Console.WriteLine("json:" + tmpJv);
            object resultObject = null;
            try
            {
                resultObject = JsonUtil.Deserialize(tmpJv, package.RespType);
            }
            catch (Exception e)
            {
                Error error = new Error(0x2000008, "无法解析异常!", resultString, e.StackTrace);
                Fault(error);
                return;
            }
            if (tmp.code > 0)
            {
                if (tmp.warning == null)
                {
                    tmp.warning = new List<Error>();
                }
                Error warning = new Error();
                warning.code = tmp.code;
                warning.cause = tmp.cause;
                warning.message = tmp.message;
                warning.stackTrace = tmp.stackTrace;

                tmp.warning.Add(warning);
            }
            Result(resultObject, tmp.warning);
            //}
            //else
            //{
            //    //Console.WriteLine("error:\n" + resultString);
            //    Result(null, tmp.warning);
            //}
        }
コード例 #6
0
 public static void AddValidation(HttpPackage package, Lin.Comm.Http.ValidationErrorData error)
 {
     IDictionary<string, object> param = package.GetParams();
     foreach (KeyValuePair<string,object> vp in param)
     {
         AddValidation(vp.Value as Lin.Core.ViewModel, error, vp.Key + ".");
     }
 }
コード例 #7
0
 public void Response(HttpPackage package, byte[] bs,Action<Object, IList<Error>> result, Action<Error> fault)
 {
     //result(resp,null);
 }
コード例 #8
0
 public byte[] GetParams(HttpWebRequest request, HttpPackage package)
 {
     return null;
 }
コード例 #9
0
        public void Request(HttpCommunicateImpl impl,HttpPackage package, Action<Object, IList<Error>> result, Action<Error> fault)
        {
            this.Result = result;
            this._fault = fault;
            this.package = package;

            try
            {
                //string urlPath = package.location;
                //string urlPath = "__http_comm_protocol__";
                //String uriString = uri.AbsoluteUri;
                //给uri加一个时间戳,阻止浏览器缓存
                //采用_time_stamp_" + DateTime.Now.Ticks做为参数名,防止url中有_time_stamp_参数名,
                //if (package.UrlType == Packages.UrlType.RELATIVE)
                //{
                    //if (package.EnableCache)
                    //{
                    //    CommUriString = impl.CommUri.AbsoluteUri;
                    //    if (CommUriString.EndsWith("/") || urlPath.StartsWith("/"))
                    //    {
                    //        uri = new Uri(CommUriString + urlPath);
                    //    }
                    //    else
                    //    {
                    //        uri = new Uri(CommUriString + "/" + urlPath);
                    //    }
                    //}
                    if(!package.EnableCache)
                    {
                        CommUriString = impl.CommUri.AbsoluteUri;

                        if (package.location.StartsWith("/"))
                        {
                            CommUriString += package.location;
                        }
                        else
                        {
                            CommUriString += "/" + package.location;
                        }
                        if (CommUriString.Contains("?"))
                        {
                            uri = new Uri(CommUriString + "&_time_stamp_" + DateTime.Now.Ticks + "=1");
                        }
                        else
                        {
                            uri = new Uri(CommUriString + "?_time_stamp_" + DateTime.Now.Ticks + "=1");
                        }
                    }

                lock (this)
                {
                    request = (HttpWebRequest)WebRequest.Create(uri);

                }
                //Console.WriteLine("proxy:" + request.Proxy);
                //request.Proxy = proxy;
                request.Method = "POST";//以POST方式传递数据
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = impl.Cookies;
                //request.Headers.Add(Constants.HTTP_COMM_PROTOCOL, Constants.HTTP_VERSION);
                //request.Timeout
                //Console.WriteLine("time out:" + request.Timeout);
                //if (package.HasParams)
                {
                    request.BeginGetRequestStream(new AsyncCallback(SetParams), request);
                }
                //else
                {
                    //request.BeginGetResponse(new AsyncCallback(RespCallback), request);
                }
                //r.AsyncWaitHandle.WaitOne();
            }
            catch (System.Exception e)
            {
                //如果有异常,表明此次请求失败
                if (_fault != null)
                {
                    Error error = new Error(0x2000002, "无法连接服务器!", e.StackTrace);
                    Fault(error);
                }
            }
            //catch (Error e) { }
        }
コード例 #10
0
 public void Response(HttpPackage package, byte[] bs, Action<object, IList<Error>> result, Action<Error> fault)
 {
     throw new NotImplementedException();
 }
コード例 #11
0
 public byte[] GetParams(HttpWebRequest request, HttpPackage package)
 {
     throw new NotImplementedException();
 }