Пример #1
0
 public override void Parse(HttpData httpData, string key)
 {
     httpData.Parameters.Add(key, JsonData.Serialize(new
     {
         force_reply = ForceReply,
         selective = Selective
     }));
 }
 public override void Parse(HttpData httpData, string key)
 {
     httpData.Parameters.Add(key, JsonData.Serialize(new
     {
         hide_keyboard = HideKeyboard,
         selective = Selective
     }));
 }
 public override void Parse(HttpData httpData, string key)
 {
     httpData.Parameters.Add(key, JsonData.Serialize(new
     {
         keyboard = Keyboard,
         resize_keyboard = ResizeKeyboard,
         one_time_keyboard = OneTimeKeyboard,
         selective = Selective
     }));
 }
Пример #4
0
        public override void Parse(HttpData httpData, string key)
        {
            switch (InputFileType)
            {
                case InputFileType.String:
                    httpData.Parameters.Add(key, FileId);
                    break;

                case InputFileType.File:
                    httpData.Files.Add(key, FileExtension, File, ContentType);
                    break;
            }
        }
Пример #5
0
        public override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId }
                }
            };

            Action?.Parse(httpData, "action");

            return httpData;
        }
Пример #6
0
        public override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "url", Url }
                }
            };

            Certificate?.Parse(httpData, "certificate");

            return httpData;
        }
Пример #7
0
        public override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            Sticker?.Parse(httpData, "sticker");
            ReplyMarkup?.Parse(httpData, "reply_markup");

            return httpData;
        }
Пример #8
0
        public override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "duration", Duration },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            Voice?.Parse(httpData, "voice");
            ReplyMarkup?.Parse(httpData, "reply_markup");

            return httpData;
        }
Пример #9
0
        public override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "caption", Caption },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            Photo?.Parse(httpData, "photo");
            ReplyMarkup?.Parse(httpData, "reply_markup");

            return httpData;
        }
Пример #10
0
        public override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "latitude", Latitude },
                    { "longitude", Longitude },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            ReplyMarkup?.Parse(httpData, "reply_markup");

            return httpData;
        }
Пример #11
0
        internal override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "duration", Duration },
                    { "caption", Caption },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            Video?.Parse(httpData, "video");
            ReplyMarkup?.Parse(httpData, "reply_markup");

            return(httpData);
        }
Пример #12
0
        /// <summary>
        /// 检查过期
        ///     可以重写
        /// </summary>
        /// <remarks>
        /// 判断是否需要重新设置Cookie
        /// </remarks>
        /// <returns>true过期;false未过期</returns>
        public override bool IsParamsExpired()
        {
            if (ParamCache == null || ParamCache.Count == 0)
            {
                return(true);
            }
            IParseSrcUrlParam ipp = this as IParseSrcUrlParam;

            AqiParam.CreateListFormSrcUrl(ipp, ipp.ParamSrcUrl);

            HttpData data = ((ICacheData)ipp.ParamSrcUrl).Data;

            if (data.Header.ContainsKey("Set-Cookie"))
            {
                return(true);
            }
            return(false);
        }
Пример #13
0
        /// <summary>
        /// Get all public methods of the library
        /// </summary>
        /// <param name="client">this</param>
        /// <param name="library">Data logic class name (it is not fully classified)</param>
        /// <returns></returns>
        public static async Task <IEnumerable <string> > GetMethodsAsync(this HttpApiClient client, string library)
        {
            string path = Flurl.Url.Combine(client.GetRequestUriString(Common.ApiPath), "methods", library);

            Uri uri = null;

            if (Uri.TryCreate(path, UriKind.Absolute, out uri))
            {
                HttpData <string> data = await client.GetAsync(uri);

                if (!string.IsNullOrWhiteSpace(data.Content))
                {
                    return(JsonConvert.DeserializeObject <IEnumerable <string> >(data.Content));
                }
            }

            return(null);
        }
Пример #14
0
        internal override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "duration", Duration },
                    { "performer", Performer },
                    { "title", Title },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            Audio?.Parse(httpData, "audio");
            ReplyMarkup?.Parse(httpData, "reply_markup");

            return(httpData);
        }
Пример #15
0
        //- @PostNewComment -//
        public Int32 PostNewComment(Int32 captchaValue, String blogEntryGuid, String author, String email, String website, String text)
        {
            Int32 returnStatus;

            //+
            if (captchaValue == HttpData.GetScopedSessionItem <Int32>("Captcha", "ExpectedValue"))
            {
                CommentReportCreator creator = new CommentReportCreator();
                creator.Formatter = new Themelia.Reporting.HtmlFormatter();
                Themelia.Map map = new Themelia.Map();
                map.Add("BlogEntryTitle", "{BlogEntryTitle}");
                map.Add("Guid", blogEntryGuid);
                map.Add("Author", author);
                map.Add("Email", email);
                map.Add("WebSite", website);
                map.Add("DateTime", DateTime.Now.ToString());
                map.Add("Text", text);
                map.Add("Link", UrlCleaner.FixWebPathTail(Minima.Configuration.BlogSection.GetConfigSection().Domain) + @"/services/comment/{CommentGuid}");
                String emailBodyTemplate = creator.Create(map);
                Themelia.Configuration.SystemSection systemSection = Themelia.Configuration.SystemSection.GetConfigSection();
                String emailSubject = String.Format("{0} ({1})", BlogSection.GetConfigSection().Comment.Subject, systemSection.AppInfo.Name);
                //+
                String commentGuid = String.Empty;
                returnStatus = 0;
                try
                {
                    commentGuid = CommentAgent.PostNewComment(blogEntryGuid, text, author, email, website, DateTime.Now, emailBodyTemplate, emailSubject);
                }
                catch (Exception ex)
                {
                    if (ex.Message != "Failure sending mail.")
                    {
                        returnStatus = 1;
                    }
                }
            }
            else
            {
                returnStatus = 2;
            }
            //+
            return(returnStatus);
        }
Пример #16
0
        /// <summary>
        /// 获取内容
        ///     可以重写
        /// </summary>
        /// <param name="param">参数列表</param>
        /// <returns></returns>
        public virtual byte[] GetData(AqiParam param)
        {
            HttpWebResponse response = null;

            try
            {
                Dictionary <string, string> header = MakeRequestHeader(param);
                switch (ParamSendType)
                {
                case AqiConstant.ParamSendType.GET:
                    string urlparam = MakeUrl(param);
                    response = HttpUtilV2.createGetResponse(urlparam, -1, header);
                    break;

                case AqiConstant.ParamSendType.POST:
                    byte[] requestbody = MakeRequestBody(param);
                    response = HttpUtilV2.createPostResponse(Url, -1, header, requestbody);
                    break;

                default:
                    throw new NotSupportedException("ParamSendType only for GET/POST");
                }
            }
            catch (System.Exception ex)
            {
                throw new DataUnHoldException("无法获取数据", ex);
            }

            HttpData data = HttpUtilV2.GetHttpData(response);

            //缓存数据
            if (this is ICacheData)
            {
                ((ICacheData)this).Data = data;
            }

            //提取数据
            if (this is IExtractData)
            {
                return(((IExtractData)this).ExtractData(data.Body));
            }
            return(data.Body);
        }
Пример #17
0
        public override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "duration", Duration },
                    { "performer", Performer },
                    { "title", Title },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            Audio?.Parse(httpData, "audio");
            ReplyMarkup?.Parse(httpData, "reply_markup");

            return httpData;
        }
Пример #18
0
        internal override HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "inline_query_id", InlineQueryId },
                    { "cache_time", CacheTime },
                    { "is_personal", IsPersonal },
                    { "next_offset", NextOffset }
                }
            };

            var results = Results.Select(r => ((BaseInlineQueryResultRequest)r).Parse()).ToArray();

            httpData.Parameters.Add("results", JsonData.Serialize(results));

            return(httpData);
        }
Пример #19
0
        //+
        //- @GetHeading -//
        private String GetHeading(AccessType accessType)
        {
            String heading = String.Empty;

            if (accessType == AccessType.Archive)
            {
                Int32  year      = HttpData.GetScopedItem <Int32>(Info.Scope, "ArchiveYear");
                Int32  month     = HttpData.GetScopedItem <Int32>(Info.Scope, "ArchiveMonth");
                String monthName = Themelia.Data.Common.Date.GetMonthData()[month];
                //+
                heading = String.Format("{0} {1}", monthName, year);
            }
            else if (accessType == AccessType.Label)
            {
                heading = HttpData.GetScopedItem <String>(Info.Scope, "LabelTitle");
            }
            //+
            return(heading);
        }
Пример #20
0
    protected void GetKaixinToken()
    {
        if (Request["code"] != null)
        {
            string client_id     = Cmn.WebConfig.getApp("app_key_kaixin");
            string client_secret = Cmn.WebConfig.getApp("app_secret_kaixin");
            string redirect_uri  = Cmn.WebConfig.getApp("app_redirectUri_kaixin");
            string grant_type    = "authorization_code";
            string code          = Request["code"].ToString();

            string          url          = "https://api.kaixin001.com/oauth2/access_token";
            string          postData     = string.Format("grant_type={2}&code={3}&client_id={0}&client_secret={1}&redirect_uri={4}", client_id, client_secret, grant_type, code, redirect_uri);
            HttpData        http         = new HttpData();
            string          responseData = http.WebRequest("post", url, postData);
            OathTokenKaixin token        = JsonHelper.ParseFormJson <OathTokenKaixin>(responseData);
            Session["access_token"] = token.access_token;
            Response.Redirect("login.aspx?s=" + Request["s"]);
        }
    }
Пример #21
0
        public HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "text", Text },
                    { "disable_web_page_preview", DisableWebPagePreview },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            if (ReplyMarkup != null)
            {
                ReplyMarkup.Parse(httpData, "reply_markup");
            }

            return(httpData);
        }
Пример #22
0
        public HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "latitude", Latitude },
                    { "longitude", Longitude },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            if (ReplyMarkup != null)
            {
                ReplyMarkup.Parse(httpData, "reply_markup");
            }

            return(httpData);
        }
Пример #23
0
        public void Parse(HttpData httpData, string key)
        {
            string action = null;

            switch (Action)
            {
            case Actions.Typing:
                action = "typing";
                break;

            case Actions.UploadPhoto:
                action = "upload_photo";
                break;

            case Actions.RecordVideo:
                action = "record_video";
                break;

            case Actions.UploadVideo:
                action = "upload_video";
                break;

            case Actions.RecordAudio:
                action = "record_audio";
                break;

            case Actions.UploadAudio:
                action = "upload_audio";
                break;

            case Actions.UploadDocument:
                action = "upload_document";
                break;

            case Actions.FindLocation:
                action = "find_location";
                break;
            }

            httpData.Parameters.Add(key, action);
        }
Пример #24
0
        public override void Parse(HttpData httpData, string key)
        {
            string action = null;

            switch (Action)
            {
                case ChatAction.Typing:
                    action = "typing";
                    break;

                case ChatAction.UploadPhoto:
                    action = "upload_photo";
                    break;

                case ChatAction.RecordVideo:
                    action = "record_video";
                    break;

                case ChatAction.UploadVideo:
                    action = "upload_video";
                    break;

                case ChatAction.RecordAudio:
                    action = "record_audio";
                    break;

                case ChatAction.UploadAudio:
                    action = "upload_audio";
                    break;

                case ChatAction.UploadDocument:
                    action = "upload_document";
                    break;

                case ChatAction.FindLocation:
                    action = "find_location";
                    break;
            }

            httpData.Parameters.Add(key, action);
        }
Пример #25
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public static bool Init()
        {
            if (_initSuccess)
            {
                return(true);
            }

            ReqData             = new HttpData();
            ReqData.Method      = RequestType.GET;
            ReqData.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            ReqData.Host        = "fanyi.baidu.com";
            ReqData.Origin      = "http://fanyi.baidu.com";
            ReqData.Referer     = "http://fanyi.baidu.com";
            ReqData.Accept      = "*/*";
            ReqData.UserAgent   = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1";
            ReqData.Data        = new Dictionary <string, string>();
            var data = InitApiUrl.HttpRequest(ReqData);

            _initSuccess = data;
            return(data);
        }
Пример #26
0
    protected void GetQQToken()
    {
        if (Request["code"] != null)
        {
            string client_id     = Cmn.WebConfig.getApp("app_key_qq");
            string client_secret = Cmn.WebConfig.getApp("app_secret_qq");
            string redirect_uri  = Cmn.WebConfig.getApp("app_redirectUri_qq");
            string grant_type    = "authorization_code";
            string code          = Request["code"].ToString();

            string              url          = "https://open.t.qq.com/cgi-bin/oauth2/access_token";
            string              postData     = string.Format("client_id={0}&client_secret={1}&grant_type={2}&code={3}&redirect_uri={4}", client_id, client_secret, grant_type, code, redirect_uri);
            HttpData            http         = new HttpData();
            string              responseData = http.WebRequest("post", url, postData);
            NameValueCollection qs           = HttpUtility.ParseQueryString(responseData);
            Session["access_token"] = qs["access_token"];
            Session["name"]         = qs["name"];
            Session["uid"]          = Request["openid"];
            Response.Redirect("myDefault.aspx?s=" + Request["s"]);
        }
    }
Пример #27
0
        public void OnClickRequest()
        {
            HttpData http = new HttpData("test", "json");

#if UNITY_5_4_OR_NEWER
            http.finishedDelegate = delegate(UnityEngine.Networking.UnityWebRequest www) {
                if (www == null)   // time over
                {
                }
                else if (www.isError)     // error
                {
                }
                else
                {
                    HellgateHttpDataEx data = JsonUtil.FromJson <HellgateHttpDataEx> (www.downloadHandler.text);
                    url = data.Url;

                    button.SetActive(true);
                }
            };
#else
            http.finishedDelegate = delegate(WWW www) {
                if (www == null)   // time over
                {
                }
                else if (www.error != null)     // error
                {
                }
                else
                {
                    HellgateHttpDataEx data = JsonUtil.FromJson <HellgateHttpDataEx> (www.text);
                    url = data.Url;

                    button.SetActive(true);
                }
            };
#endif

            HttpManager.Instance.Get(http);
        }
Пример #28
0
        public HttpData Parse()
        {
            var httpData = new HttpData
            {
                Parameters = new HttpParameterList
                {
                    { "chat_id", ChatId },
                    { "reply_to_message_id", ReplyToMessageId }
                }
            };

            if (Video != null)
            {
                Video.Parse(httpData, "video");
            }
            if (ReplyMarkup != null)
            {
                ReplyMarkup.Parse(httpData, "reply_markup");
            }

            return(httpData);
        }
Пример #29
0
        public string GetDescription(string link_url)
        {
            HttpData httpData = new HttpData();

            string str = httpData.StringFromUrl(link_url);

            string result = "";

            string signContend = "<p><b>";

            int start_index = str.IndexOf(signContend, 0);

            int end_index = str.IndexOf("</p>", start_index + (signContend.Length));


            result = str.Substring(start_index + (signContend.Length), (end_index - (start_index + (signContend.Length))));

            //System.Diagnostics.Debug.WriteLine("Des: " + result);


            return(result);
        }
Пример #30
0
    protected void GetRenRenToken()
    {
        if (Request["code"] != null)
        {
            string client_id     = Cmn.WebConfig.getApp("app_key_renren");
            string client_secret = Cmn.WebConfig.getApp("app_secret_renren");
            string redirect_uri  = Cmn.WebConfig.getApp("app_redirectUri_renren");
            string grant_type    = "authorization_code";
            string code          = Request["code"].ToString();

            string   url          = "https://graph.renren.com/oauth/token";
            string   postData     = string.Format("grant_type={2}&client_id={0}&redirect_uri={4}&client_secret={1}&code={3}", client_id, client_secret, grant_type, code, redirect_uri);
            HttpData http         = new HttpData();
            string   responseData = http.WebRequest("post", url, postData);

            var decodedJSON = JObject.Parse(responseData);
            Session["uid"]          = decodedJSON["user"]["id"];
            Session["uname"]        = decodedJSON["user"]["name"];
            Session["access_token"] = decodedJSON["access_token"];
            Response.Redirect("myDefault.aspx?s=" + Request["s"]);
        }
    }
Пример #31
0
        /// <summary>
        /// 加载参数
        ///     可以重写
        /// </summary>
        /// <remarks>
        /// 获取DSId与Cookie
        /// </remarks>
        /// <returns></returns>
        public override bool LoadParams()
        {
            bool result = base.LoadParams();

            if (result)
            {
                IParseSrcUrlParam ipp          = this as IParseSrcUrlParam;
                AqiParam          dsidAqiParam = AqiParam.CreateListFormSrcUrl(ipp, ipp.ParamSrcUrl)[0];
                HttpData          data         = ((ICacheData)ipp.ParamSrcUrl).Data;

                foreach (AqiParam param in ParamCache)
                {
                    param["DSId"] = dsidAqiParam["DSId"];
                    if (data.Header.ContainsKey("Set-Cookie"))
                    {
                        param.Header["Cookie"] = data.Header["Set-Cookie"];
                    }
                }
            }

            return(result);
        }
Пример #32
0
 //+
 //- @ProcessRequest -//
 public override void Process()
 {
     if (Themelia.Web.Http.GetUrlPart(Themelia.Position.Penultima) == "imagestore")
     {
         Byte[] buffer      = HttpData.GetInputHttpByteArray();
         String contentType = HttpData.GetHeaderItem(Info.ImageContentType);
         if (buffer != null && buffer.Length > 0 && !String.IsNullOrEmpty(contentType))
         {
             String    blogGuid  = Themelia.Web.Http.GetUrlPart(Themelia.Position.Ultima);
             BlogImage blogImage = new BlogImage
             {
                 ContentType = contentType,
                 Data        = buffer
             };
             //+
             try
             {
                 Response.Write(ImageAgent.SaveImage(blogImage, blogGuid));
             }
             catch
             {
             }
         }
         else
         {
             String blogImageGuid = Themelia.Web.Http.GetUrlPart(Themelia.Position.Ultima);
             if (!String.IsNullOrEmpty(blogImageGuid))
             {
                 BlogImage blogImage = ImageAgent.GetImage(blogImageGuid);
                 if (blogImage.Data != null && blogImage.Data.Length > 0)
                 {
                     ContentType = blogImage.ContentType;
                     Response.BinaryWrite(blogImage.Data);
                 }
             }
         }
     }
 }
Пример #33
0
        public static async Task <HttpDataExpando> GetDynamicDataAsync(this HttpApiClient client,
                                                                       string library, string method, object[] values, PropMold[] props)
        {
            List <dynamic> result = new List <dynamic>();

            HttpData <object[]> data = await client.GetDataAsync <object>(library, method, values);

            dynamic expandoObject = Helpers.MakeExpandoWithDefaults(props);
            bool    successFlag   = true;

            foreach (JObject item in data.Content)
            {
                // Data item type is Newtonsoft.Json.Linq.JObject
                string  json   = item.ToString();
                dynamic output = null;
                try
                {
                    output = JsonConvert.DeserializeAnonymousType(json, expandoObject);
                }
                catch (Exception ex)
                {
                    client.OnErrorOccured(new HttpErrorEventArgs(
                                              ex, data.RequestUri.ToString(), HttpVerb.Get, "Invalid response format. JSON expected."));
                    successFlag = false;
                }

                if (successFlag)
                {
                    result.Add(output);
                }
                else
                {
                    break;
                }
            }

            return(new HttpDataExpando(data, result.ToArray()));
        }
Пример #34
0
 public override HttpData Parse()
 {
     var httpData = new HttpData
     {
         Parameters = new HttpParameterList
         {
             { "chat_id", ChatId },
             { "text", Text },
             { "disable_web_page_preview", DisableWebPagePreview },
             { "reply_to_message_id", ReplyToMessageId }
         }
     };
     string parseMode = null;
     switch (ParseMode)
     {
         case ParseMode.Markdown:
             parseMode = "Markdown";
             break;
     }
     httpData.Parameters.Add("parse_mode", parseMode);
     ReplyMarkup?.Parse(httpData, "reply_markup");
     return httpData;
 }
 /// <summary>
 /// Requests the post.
 /// </summary>
 /// <returns><c>true</c>, if post was requested, <c>false</c> otherwise.</returns>
 /// <param name="info">Info.</param>
 /// <param name="timeout">Timeout.</param>
 public bool RequestPost(HttpBase info, int timeout = 10)
 {
     if (info.islog)
     {
         Debug.Log("request post; url:" + info.url);
     }
     if (this.CheckInterNet())
     {
         HttpData httpData = new HttpData();
         ++id;
         httpData.id          = id;
         httpData.timeout     = timeout;
         httpData.requetime   = System.DateTime.Now;
         httpData.httpbase    = info;
         httpData.httpRequest = HttpPost(httpData);
         httpdatas.Add(id, httpData);
         StartCoroutine(httpData.httpRequest);
         return(true);
     }
     else
     {
         return(false);
     }
 }
 /// <summary>
 /// Requests the delete.
 /// </summary>
 /// <returns><c>true</c>, if delete was requested, <c>false</c> otherwise.</returns>
 /// <param name="httpBase">Http base.</param>
 /// <param name="timeout">Timeout.</param>
 public bool RequestDelete(HttpBase httpBase, int timeout = 10)
 {
     if (httpBase.islog)
     {
         Debug.Log("request delete; url" + httpBase.url);
     }
     if (this.CheckInterNet())
     {
         HttpData httpData = new HttpData();
         ++id;
         httpData.id          = id;
         httpData.timeout     = timeout;
         httpData.requetime   = System.DateTime.Now;
         httpData.httpbase    = httpBase;
         httpData.httpRequest = HttpDelete(httpData);
         httpdatas.Add(id, httpData);
         StartCoroutine(httpData.httpRequest);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #37
0
        private void cancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (ViewState != null)
            {
                List<UIElement> person = new List<UIElement>() { cardCredit, cardDiscount, firstname, surname, name, phone, email };
                foreach (TextBox tb in person)
                {
                    tb.Foreground = tb.BorderBrush = tb.SelectionBrush = brushDEFAULT as Brush;
                }

                Common.card = ViewState.Copy();
                ViewState = new HttpData();
                dataChanged = false;
                getCard(true);
            }
        }
    /**POST*/
    private IEnumerator HttpPost(HttpData httpData)
    {
        UnityWebRequest request = new UnityWebRequest(httpData.httpbase.url, UnityWebRequest.kHttpVerbPOST);

        byte[] data = System.Text.Encoding.Default.GetBytes(httpData.httpbase.GetData());
        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(data);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

        request.SetRequestHeader("Content-Type", "application/json");
        Dictionary <string, string> header = httpData.httpbase.GetHeaders();

        if (header != null)
        {
            foreach (KeyValuePair <string, string> post_arg in header)
            {
                request.SetRequestHeader(post_arg.Key, post_arg.Value);
            }
        }
        DateTime beginTime = DateTime.Now;

        yield return(request.Send());

        httpData.backtime     = DateTime.Now;
        httpData.durationtime = (httpData.backtime - beginTime).TotalMilliseconds;

        if (httpData.httpbase.islog)
        {
            Debug.Log("request time :" + (httpData.backtime - beginTime).TotalMilliseconds);
            Debug.Log("responseCode:" + request.responseCode);
            Debug.Log("request web:" + request.downloadHandler.text);
        }
        if (request.isDone)
        {
            string webData = request.downloadHandler.text;
            if (httpData.httpbase.islog)
            {
                Debug.Log("post back:" + webData);
            }
            httpData.webData      = webData;
            httpData.responseCode = request.responseCode;
            if (request.responseCode == 200)
            {
                httpData.httpbase.HttpRequesSuccess(httpData);
            }
            else
            {
                httpData.httpbase.HttpRequesFail(httpData);
            }
        }
        request.Dispose();

        if (httpdatas.ContainsKey(id))
        {
            httpdatas.Remove(id);
        }

        if (httpData.httpbase.islog)
        {
            Debug.Log("POST END " + httpData.httpbase.url);
        }
    }
Пример #39
0
 internal abstract void Parse(HttpData httpData, string key);
Пример #40
0
        // public static List<WeatherObject> lstWeathers = new List<WeatherObject>();


        public List <WeatherObject> GetDataWeather3days()
        {
            List <WeatherObject> lstWeathers = new List <WeatherObject>();

            HttpData httpData = new HttpData();
            string   json     = httpData.StringFromUrl("http://api.openweathermap.org/data/2.5/forecast?q=Hanoi&appid=453834abf4e4465bbd71a8221489040e");

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            dynamic dobj = jsonSerializer.Deserialize <dynamic>(json);

            object timeToday  = dobj["list"][0]["dt_txt"].ToString();
            string currentDay = "Hôm nay";

            string currentTimeToday = timeToday.ToString();

            string[] strTimeTodayCut = currentTimeToday.Split(' ');
            string   strToday        = strTimeTodayCut[0];
            string   strCurrentDay   = strToday;

            for (int i = 0; i < 20; i++)
            {
                object temp   = dobj["list"][i]["main"]["temp"].ToString();
                object status = dobj["list"][i]["weather"][0]["description"].ToString();
                object time   = dobj["list"][i]["dt_txt"].ToString();

                WeatherObject weatherObject = new WeatherObject();

                weatherObject.Temp = ConvertTempKtoTempC(temp.ToString());



                weatherObject.Status = status.ToString();
                weatherObject.Time   = time.ToString();

                string[] strTimeCut = time.ToString().Split(' ');
                string   strDay     = strTimeCut[0];

                if (!strCurrentDay.Equals(strDay.ToString()) && currentDay.Equals("Hôm nay"))
                {
                    currentDay    = "Ngày mai";
                    strCurrentDay = strDay.ToString();
                }

                if (!strCurrentDay.Equals(strDay.ToString()) && currentDay.Equals("Ngày mai"))
                {
                    currentDay    = "Ngày kia";
                    strCurrentDay = strDay.ToString();
                }

                weatherObject.Day = currentDay;

                lstWeathers.Add(weatherObject);
            }


            WeatherObject datageted = new WeatherObject();

            datageted = lstWeathers[0];

            return(lstWeathers);
        }
Пример #41
0
        // Parse card to UIElements
        private void getCard(bool firstload = false)
        {
            if (firstload)
            {
                dataChanged = false;
                FirstLoad = true;
            }

            if (card.errcode == ErrCodes.CardNotFound)
            {
                initDefault();
                cardId.Content = card.card;

                cardValidity.IsChecked = true;

                if (!ApplicationSettings.DEBIT)
                {
                    cardType.SelectedIndex = 1;
                }
                else
                {
                    cardType.SelectedIndex = 2;
                }

                ownState = OwnerState.New;
                UserContolState(firstload);

                if (firstload) ViewState = Common.card.Copy();

                ev(this, new MainEventArgs() { ev = Event.popUp, animType = AnimType.PopUp, menuChange = Menu.NotFound });
            }
            else if (card.errcode == ErrCodes.PersonNoMatchFound)
            {
                cardId.Content = SubView.card;
                cardValidity.IsChecked = (SubView.validity == 0) ? false : true;
                cardType.SelectedIndex = (SubView.type == CardType.SERVICE) ? 4 : (int)SubView.type;

                cardCredit.Text = String.Format(new CultureInfo(ConfigurationManager.AppSettings["Culture"]), "{0:F2}", SubView.credit);
                cardBalance.Text = String.Format(new CultureInfo(ConfigurationManager.AppSettings["Culture"]), "{0:F2}", SubView.saldo);

                cardLimit.Text = String.Format(new CultureInfo(ConfigurationManager.AppSettings["Culture"]), "{0:F2}", SubView.limit);
                cardDiscount.Text = String.Format("{0}", SubView.discount);
            }
            else
            {
                cardId.Content = Common.card.card;
                cardValidity.IsChecked = (Common.card.validity == 0) ? false : true;
                cardType.SelectedIndex = (Common.card.type == CardType.SERVICE) ? 4 : (int)Common.card.type;

                cardCredit.Text = String.Format(new CultureInfo(ConfigurationManager.AppSettings["Culture"]), "{0:F2}", Common.card.credit);
                cardBalance.Text = String.Format(new CultureInfo(ConfigurationManager.AppSettings["Culture"]), "{0:F2}", Common.card.saldo);

                cardLimit.Text = String.Format(new CultureInfo(ConfigurationManager.AppSettings["Culture"]), "{0:F2}", Common.card.limit);
                cardDiscount.Text = String.Format("{0}", Common.card.discount);

                Common.clientID = Common.card.a08id;
                name.Text = Common.card.name;
                firstname.Text = Common.card.firstname;
                surname.Text = Common.card.surname;
                email.Text = Common.card.email;
                phone.Text = Common.card.phone;

                if (Common.fillCard == true)
                {
                    UserContolState(false);
                    Common.fillCard = false;
                }
                else
                {
                    UserContolState(firstload);
                }

                if (firstload) ViewState = Common.card.Copy();
            }

            if (firstload) FirstLoad = false;
        }
Пример #42
0
 public abstract void Parse(HttpData httpData, string key);
Пример #43
0
    public override string GetIpsByHttpDNS(string url)
    {
        if (url.StartsWith("http://"))
        {
            url = url.Replace("http://", "");
        }
        if (ipCache.ContainsKey(url))
        {
            return(ipCache[url]);
        }
        //181184
        //198540
        WWWUtil.Get("http://203.107.1.1/181184/d?host=" + url).Subscribe(x => {
            if (x.text.StartsWith("{"))
            {
                HttpData HttpData = JsonUtility.FromJson <HttpData>(x.text);
                // Debug.Log(HttpData.host);
                // Dictionary<string, object> dic = JsonUtility.Deserialize(x.text) as Dictionary<string, object>;
                // if (dic.ContainsKey("host")) {
                //  var ips = dic["ips"] as List<object>;
                nextUpdateTime = Time.realtimeSinceStartup + HttpData.ttl;
                string ipList  = "";
                foreach (var ip in HttpData.ips)
                {
                    if (!string.IsNullOrEmpty(ipList))
                    {
                        ipList += ",";
                    }
                    if (!string.IsNullOrEmpty(ip as string))
                    {
                        ipList += ip as string;
                    }
                }
                string data = JsonUtility.ToJson(new CustomEventData()
                {
                    eventName = "onGetIpsByHttpDNSResult",
                    data      = ipList
                });


                GameSDKCallback.instance.OnSdkCallbackCall(data);

                data = JsonUtility.ToJson(new CustomEventData()
                {
                    eventName = "onAppstorePaySucess",
                    data      = ""
                });
                GameSDKCallback.instance.OnSdkCallbackCall(data);
                if (!string.IsNullOrEmpty(ipList))
                {
                    if (ipCache.ContainsKey(url))
                    {
                        ipCache[url] = ipList;
                    }
                    else
                    {
                        ipCache.Add(url, ipList);
                    }
                }
            }
        }, e => {
            Debug.LogError("GetIpsByHttpDNS:" + e.error);
        });

        return(url);
    }
Пример #44
0
 private static bool CheckDataContent(HttpData <string> data) =>
 data.IsSuccessStatusCode && !string.IsNullOrWhiteSpace(data.Content) &&
 data.ContentType.MediaType.Contains("json");
Пример #45
0
    protected void GetSinaToken()
    {
        if (Request["code"] != null)
        {
            string client_id     = Cmn.WebConfig.getApp("app_key_sina");
            string client_secret = Cmn.WebConfig.getApp("app_secret_sina");
            string redirect_uri  = Cmn.WebConfig.getApp("app_redirectUri_sina");
            string grant_type    = "authorization_code";
            string code          = Request["code"].ToString();

            string    url          = "https://api.weibo.com/oauth2/access_token";
            string    postData     = string.Format("client_id={0}&client_secret={1}&grant_type={2}&code={3}&redirect_uri={4}", client_id, client_secret, grant_type, code, redirect_uri);
            HttpData  http         = new HttpData();
            string    responseData = http.WebRequest("post", url, postData);
            OathToken token        = JsonHelper.ParseFormJson <OathToken>(responseData);

            Cmn.Cookies.Set("access_token", token.access_token, 7);
            Cmn.Cookies.Set("uid", token.uid, 7);

            //============
            string strUrl = string.Format("https://api.weibo.com/2/users/show.json?access_token={0}&uid={1}",
                                          token.access_token, token.uid);
            string myJson                = http.WebRequest("get", strUrl, string.Empty);
            var    decodedJSON           = JObject.Parse(myJson);
            var    SinaScreen_name       = decodedJSON["screen_name"].ToString() + "_sina";
            var    SinaProfile_image_url = decodedJSON["profile_image_url"];
            var    sinaId                = decodedJSON["id"];
            //=======
            //查找会员社区表中,是否已经存在
            int    uIdx            = 0;
            string SinaPhotoHeader = Cmn.Date.ToDateStr2(DateTime.Now) + "_" + sinaId + ".png";
            string strSql          = string.Format("select count(1) from Tab_UserCommunity where SinaWeibo_Id='{0}'", sinaId);
            int    iCount          = Convert.ToInt32(SqlHelper.ExecuteScalar(CommandType.Text, strSql));
            Cmn.Log.Write("strSql=" + strSql + "|iCount=" + iCount);

            if (iCount == 0)
            {
                //保存头像
                using (WebClient wc = new WebClient())
                {
                    string photoUrl = SinaProfile_image_url.ToString();

                    string photoSavePath = Server.MapPath("~/upload/userHearderImg/") + SinaPhotoHeader;
                    wc.DownloadFile(photoUrl, photoSavePath);
                }

                //添加到数据库

                DBEntity.Tab_UserCommunity ent2 = new DBEntity.Tab_UserCommunity();
                ent2.UserEmail    = SinaScreen_name.ToString();
                ent2.RealName     = SinaScreen_name.ToString();
                ent2.VipBool      = "no";
                ent2.Password     = "******";
                ent2.City         = "";
                ent2.HeadPhoto    = SinaPhotoHeader;
                ent2.SinaWeibo_Id = sinaId.ToString();
                uIdx = ent2.AddNew(ent2);
            }

            strSql = string.Format("insert into Tab_User_LoginLog (LoginName,LoginIpAddress) values('{0}','{1}')", SinaScreen_name, Request.UserHostAddress);
            SqlHelper.ExecuteNonQuery(CommandType.Text, strSql);


            DBEntity.Tab_UserCommunity ent = DBEntity.Tab_UserCommunity.GetBySinaId(sinaId.ToString());

            uIdx = Convert.ToInt32(ent.Idx);
            int remeberDay = 7;
            Cmn.Cookies.Set("login_UserIdx", uIdx.ToString(), remeberDay);
            Cmn.Cookies.Set("login_UserEmail", ent.UserEmail, remeberDay);
            Cmn.Cookies.Set("login_RealName", ent.RealName, remeberDay);
            Cmn.Cookies.Set("login_VipBool", ent.VipBool, remeberDay);
            Cmn.Cookies.Set("login_HeadPhoto", string.Format("{0}/upload/userHearderImg/{1}", Cmn.WebConfig.getApp("app_WebsiteDomain"), ent.HeadPhoto), remeberDay);
            Cmn.Log.Write(Cmn.Cookies.Get("login_UserEmail"));


            //========= End


            Response.Redirect("index.aspx?s=" + Request["s"]);
        }
    }
        /// <summary>
        /// Sets data regarding the current HTTP request.
        /// A URL and method must be set.
        /// </summary>
        /// <param name="request">Information regarding the current request.</param>
        public SentryEventBuilder SetRequestData(HttpData request)
        {
            _requestData = request;

            return(this);
        }