예제 #1
0
 public PlaceDetailsPage(PostDataType postDataType)
 {
     postData      = postDataType;
     relatedFilter = PostType.Place;// default filter is place whear everyting is showing
     this.Title    = postData.Title;
     Init();
 }
        /// <summary>
        ///  send post request
        /// </summary>
        public static async Task <HttpResponse> PostAsync <TRequestData>(this IHttpService http,
                                                                         string url,
                                                                         TRequestData requestData,
                                                                         PostDataType dataType)
            where TRequestData : class
        {
            if (dataType == PostDataType.Json)
            {
                string content = JsonConvert.SerializeObject(requestData, JsonSerializerConfig.SerializerSettings);

                return(await http.PostAsync(url, content));
            }
            else if (dataType == PostDataType.FormData)
            {
                var list = new List <KeyValuePair <string, object> >();
                foreach (var item in requestData.GetType().GetProperties())
                {
                    list.Add(new KeyValuePair <string, object>(item.Name.ToLower(), item.GetValue(requestData, null)));
                }

                return(await http.PostAsync(url, list));
            }
            else
            {
                throw new NotImplementedException();
            }
        }
예제 #3
0
 /// <summary>
 /// Additional default constructer to define a place with specific type of related posts..
 /// for ex: place with mistakes only, or place with supplications only. etc..
 /// </summary>
 /// <param name="postDataType"> that has post and anlylize its content</param>
 /// <param name="relatedPostFilter"> the type of related posts which we need the filter with it</param>
 public PlaceDetailsPage(PostDataType postDataType, PostType relatedPostFilter, string title)
 {
     postData      = postDataType;
     relatedFilter = relatedPostFilter;
     this.Title    = title;
     Init();
 }
예제 #4
0
        /// <summary>
        /// Post data to server API.
        /// </summary>
        /// <param name="apiUrl">Sever API uri</param>
        /// <param name="type">Post data type</param>
        /// <param name="data">Contents to send.</param>
        /// <param name="onSuccess">Action triggered if post to server API is successful</param>
        /// <param name="onFailure">Action triggered if post to server API failed</param>
        /// <param name="uuid">Object to delete UUID</param>
        public async void PostData(string apiUrl, PostDataType type, Dictionary <string, string> data = null,
                                   Action <string> onSuccess = null, Action <string> onFailure = null, string uuid = null)
        {
            FormUrlEncodedContent content;

            switch (type)
            {
            case PostDataType.Post:
                content = new FormUrlEncodedContent(data);

                using (var response =
                           await ApiHelper.ApiClient.PostAsync(ApiHelper.ApiClient.BaseAddress + apiUrl, content))
                {
                    Action(response);
                }
                break;

            case PostDataType.Put:
                content = new FormUrlEncodedContent(data);

                using (var response =
                           await ApiHelper.ApiClient.PutAsync(ApiHelper.ApiClient.BaseAddress + apiUrl, content))
                {
                    Action(response);
                }
                break;

            case PostDataType.Delete:
                using (var response =
                           await ApiHelper.ApiClient.DeleteAsync(
                               ApiHelper.ApiClient.BaseAddress + apiUrl + "?uuid=" + uuid))
                {
                    Action(response);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            async void Action(HttpResponseMessage response)
            {
                if (response.IsSuccessStatusCode)
                {
                    onSuccess?.Invoke(JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync())
                                      .ToString());
                }
                else
                {
                    onFailure?.Invoke(response.ReasonPhrase);
                }
            }
        }
예제 #5
0
        public DetailPage(PostDataType postDataType)
        {
            postData   = postDataType;
            this.Title = postData.Title;

            if (postData.Post == null)
            {
                return;
            }

            this.TitleIconUri = postData.GetTitleIconUri();
            InitializeControls();
        }
        /// <summary>
        ///  send post request
        /// </summary>
        public static async Task <HttpResponse <TResultData> > PostAsync <TResultData>(
            this IHttpService http,
            string url,
            object requestData,
            PostDataType dataType = PostDataType.Json)
            where TResultData : JsonResultModel
        {
            HttpResponse result = await http.PostAsync(url, requestData, dataType);

            if (result.Success && !string.IsNullOrEmpty(result.RawString))
            {
                return(result.Load(result.RawString.ToJsonResultModel <TResultData>()));
            }

            return(result.Load(default(TResultData)));
        }
예제 #7
0
        /// <summary>
        /// Returns the parameters array formatted for multi-part/form data
        /// </summary>
        /// <returns></returns>
        public string GetPostData(PostDataType DataType = PostDataType.Multipart)
        {
            if (DataType == PostDataType.UrlEncoded)
            {
                return(this.GetUrlEncodedString());
            }
            else if (DataType == PostDataType.Json)
            {
                return(this.Get("json").Value.IsNullOrEmpty() ? this.Get("body").Value : this.Get("json").Value);
            }

            StringBuilder sb = new StringBuilder();

            foreach (PostDataParam p in Params)
            {
                sb.AppendLine("--" + boundary);

                if (p.Type == PostDataParamType.File)
                {
                    string type = System.Net.Mime.MediaTypeNames.Application.Octet;

                    if (p.FileName.RegexHasMatches("\\.jp[e]?g$"))
                    {
                        type = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                    }
                    else if (p.FileName.RegexHasMatches("\\.png$"))
                    {
                        type = "image/png";
                    }

                    sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
                    sb.AppendLine("Content-Type: " + type);
                    sb.AppendLine();
                    sb.AppendLine(p.Value);
                }
                else
                {
                    sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
                    sb.AppendLine();
                    sb.AppendLine(p.Value);
                }
            }

            sb.AppendLine("--" + boundary + "--");

            return(sb.ToString());
        }
예제 #8
0
 public void Initdata()
 {
     _URL = string.Empty;
     _Method = "GET";
     _Timeout = 100000;
     _ReadWriteTimeout = 30000;
     _KeepAlive = true;
     _Accept = "text/html, application/xhtml+xml, */*";
     _ContentType = "text/html";
     _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
     _Encoding = null;
     _PostDataType = PostDataType.String;
     _Postdata = string.Empty;
     _PostdataByte = null;
     _WebProxy = null;
     cookiecollection = null;
     _Cookie = string.Empty;
     _Referer = string.Empty;
     _CerPath = string.Empty;
     isToLower = false;
     allowautoredirect = false;
     connectionlimit = 1024;
     proxyusername = string.Empty;
     proxypwd = string.Empty;
     proxyip = string.Empty;
     resulttype = ResultType.String;
     header.Clear();// = new WebHeaderCollection();
     _ProtocolVersion = System.Net.HttpVersion.Version11;
     _expect100continue = true;
     _ClentCertificates = null;
     _PostEncoding = Encoding.Default;
     _ResultCookieType = ResultCookieType.String;
     _ICredentials = CredentialCache.DefaultCredentials;
 }
예제 #9
0
        private static RespCode LinkServer(string _url, string _objModel, string _accessToken = null,
                                           string _Method = "Post", PostDataType pdType = PostDataType.Byte)
        {
            sw.Start();
            sw.Restart();

            Log4NetHelper.Debug(String.Format("HTTP 请求地址:{0}。", _url));

            Log4NetHelper.Debug(String.Format("HTTP 请求参数:{0}。", _objModel));

            //创建Httphelper对象
            HttpHelper http = new HttpHelper();

            WebHeaderCollection header = new WebHeaderCollection();

            if (!string.IsNullOrEmpty(_accessToken))
            {
                //header.Add("accessToken", _accessToken);
                _url = $"{_url}?token={_accessToken}";
            }

            if (_Method.Trim().ToLower() == "get" && !string.IsNullOrEmpty(_objModel))
            {
                _url = $"{_url}?{_objModel}";
            }


            //header.Add("User-Agent", $"yys-PlatformID.Windows-{MachineInfoHelper.LD?.currentVersion}");
            //创建Httphelper参数对象
            HttpItem item = new HttpItem()
            {
                URL              = _url,
                Method           = _Method,
                Timeout          = 1000 * 30,
                ReadWriteTimeout = 1000 * 30,
                //Header = header,
                UserAgent = $"yys-PlatformID.Windows-{MachineInfoHelper.LD?.currentVersion}",
                //Encoding = Encoding.Default,
                PostEncoding = Encoding.UTF8,
                //Header = wcHeader,
                ContentType  = "application/x-www-form-urlencoded;charset=utf-8", //"application/json",
                PostDataType = pdType,
                //PostdataByte = fileData,
                Postdata = _objModel, //"nowTick=" + DateTime.Now.Ticks.ToString("x"),
            };

            //请求的返回值对象
            HttpResult result = http.GetHtml(item);
            string     html   = result.Html;
            //string cookie = result.Cookie;

            var resp = JsonHelper.FromJson <RespCode>(html);

            Log4NetHelper.Debug(String.Format("HTTP 响应内容:{0}。", html));

            if (result.StatusCode != HttpStatusCode.OK)
            {
                Log4NetHelper.Error(String.Format("HTTP 请求参数:{0},响应内容 请求失败 ---> {1}。", _objModel, JsonHelper.ToJson(result)));

                if (resp == null)
                {
                    resp = new RespCode()
                    {
                        retCode = 40400,
                        retMsg  = "网络连接失败,请检查后重试!",
                        retData = "",
                        retHtml = JsonHelper.ToJson(result)
                    };
                }
                else
                {
                    resp.retCode = 40400;
                    resp.retMsg  = "网络连接失败,请检查后重试!";
                    resp.retHtml = JsonHelper.ToJson(result);
                }
            }

            sw.Stop();
            TimeSpan ts2 = sw.Elapsed;

            Log4NetHelper.Debug(String.Format("LinkServer 执行时间:{0}s。", ts2.TotalSeconds));
            sw.Reset();

            return(resp);
        }