Example #1
0
        /// <summary>
        /// 配置使用的Content
        /// </summary>
        /// <param name="reqMsg">请求消息</param>
        /// <param name="request">Http请求参数</param>
        private static void ConfigReqContent(HttpRequestMessage reqMsg, HttpRequestParameter request)
        {
            if (request.Method == Enums.HttpMethod.Get)
            {
                return;
            }
            string boundary = null;

            if (request.HasFile)
            {
                boundary = GetBoundary();
                var memory = new MemoryStream();
                WriteMultipartFormData(memory, request, boundary);
                memory.Seek(0, SeekOrigin.Begin);//设置指针到起点
                reqMsg.Content = new StreamContent(memory);
            }
            else
            {
                string data = GetNormalFormData(request);
                reqMsg.Content = new StringContent(data);
                reqMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            }
            request.RequestSettings?.Invoke(reqMsg);// 位置不能变,防止外部修改 Content-Type
            if (request.HasFile)
            {
                reqMsg.Content.Headers.Remove("Content-Type");
                reqMsg.Content.Headers.TryAddWithoutValidation("Content-Type",
                                                               $"multipart/form-data;boundary={boundary}");
            }
        }
 /// <summary>
 /// Represents a method to delete a user profile with email confirmation. 
 /// </summary>
 /// <param name="userid">A userid is set of unique numerics and characters that uniquely identifies a user.</param>
 /// <param name="deleteuserlink">Delete user link is an URL which handles the logic of deleting a user and this URL is to be emailed to the user for confirmation.</param>
 public LoginRadiusPostResponse DeleteUser(string userid, string deleteuserlink)
 {
     _validate.Validate(_valuesToCheck = new ArrayList() { userid,deleteuserlink }, "GetUser");
     var getRequest = new HttpRequestParameter { { "userid", userid }, { "deleteuserlink", deleteuserlink } };
     var response = Get(_object, getRequest);
     return response.Deserialize<LoginRadiusPostResponse>();
 }
Example #3
0
        public string Request(string url, HttpRequestParameter parameter, HttpMethod method, HttpHeader headers)
        {
            string _params = string.Empty;

            if (parameter != null && parameter.Count > 0)
            {
                _params = parameter.ToString();
            }

            if (method == HttpMethod.GET)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + _params;
                }
                else
                {
                    url = url + "?" + _params;
                }

                return HttpGet(url, headers);
            }
            else
            {
                return HttpPost(url, _params, headers);
            }
        }
 /// <summary>
 /// Method checks for the existence of the specified email address in your Cloud Storage.
 /// </summary>
 /// <param name="emailId">Email address.</param>
 public LoginRadiusEmailResponse CheckUserEmail(string emailId)
 {
     _valuesToCheck = new ArrayList {emailId};
     _validate.Validate(_valuesToCheck, "Check User Email");
     var getRequest = new HttpRequestParameter { { "email", emailId } };
     var response = Get(_object.ChildObject("checkemail"), getRequest);
     return response.Deserialize<LoginRadiusEmailResponse>();
 }
Example #5
0
        public HttpResponse HttpPostJson(string uri, HttpRequestParameter getHttpParameters, string json)
        {
            if (getHttpParameters != null && getHttpParameters.Count > 0)
            {
                uri = getHttpParameters.ToString(uri);
            }

            return HttpPost(uri, json, "application/json");
        }
Example #6
0
        private HttpResponse HttpPutXml(string uri, HttpRequestParameter getHttpParameters, string xml)
        {
            if (getHttpParameters != null && getHttpParameters.Count > 0)
            {
                uri = getHttpParameters.ToString(uri);
            }

            return HttpPut(uri, xml, "application/xml");
        }
Example #7
0
        public HttpResponse HttpGet(string uri, HttpRequestParameter httpParameters)
        {
            if (httpParameters != null && httpParameters.Count > 0)
            {
                uri = httpParameters.ToString(uri);
            }

            return HttpRequest(uri, null, "GET", "application/json");
        }
 private LoginRadiusV2EntityBase(UserRegistrationAuthentication authentication)
 {
     Authentication = authentication;
     _commHttpRequestParameter = new HttpRequestParameter()
     {
         {"key", Authentication.UserRegistrationKey},
         {"secret", Authentication.UserRegistrationSecret}
     };
 }
Example #9
0
        public HttpResponse HttpPost(string uri, HttpRequestParameter getHttpParameters, HttpRequestParameter postHttpParameters)
        {
            if (getHttpParameters != null && getHttpParameters.Count > 0)
            {
                uri = getHttpParameters.ToString(uri);
            }

            return HttpPost(uri, postHttpParameters.ToString(), "application/x-www-form-urlencoded");
        }
        /// <summary>
        /// Represents a method that retrieves the profile data associated with the specific user using the passing in email address.
        /// </summary>
        /// <param name="emailId">An email is an unique set of characters and numerics that uniquely identifies a user or email address.</param>
        public RaasUserprofile GetUserbyEmail(string emailId)
        {
            _validate.Validate(_valuesToCheck = new ArrayList() { emailId }, "GetUser");

            var getRequest = new HttpRequestParameter { { "email", emailId } };

            var response = Get(_object, getRequest);

            return response.Deserialize<RaasUserprofile>();
        }
Example #11
0
        /// <summary>
        /// 执行请求方法
        /// </summary>
        /// <param name="client">Http客户端</param>
        /// <param name="request">Http请求参数</param>
        /// <param name="completionOption">Http完成操作</param>
        /// <param name="cancellationToken">取消操作通知</param>
        /// <returns></returns>
        public static Task <HttpResponseMessage> SendReq(this HttpClient client, HttpRequestParameter request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
        {
            var reqMsg = ConfigureReqMsg(request);

            if (request.TimeOut > 0)
            {
                client.Timeout = TimeSpan.FromMilliseconds(request.TimeOut);
            }
            return(client.SendAsync(reqMsg, completionOption, cancellationToken));
        }
        /// <summary>
        /// Represents a method for profile data and authentication of a user. 
        /// </summary>
        /// <param name="username">A username is a name or email that uniquely identifies a user.</param>
        /// <param name="password">A password is a string of characters used for authenticating a user.</param>
        public RaasUserprofile GetUser(string username, string password)
        {
            _validate.Validate(_valuesToCheck = new ArrayList() { username, password }, "GetUser");

            var getRequest = new HttpRequestParameter { { "username", username }, { "password", password } };

            var response = Get(_object, getRequest);

            return response.Deserialize<RaasUserprofile>();
        }
        /// <summary>
        /// Method to authenticate users and returns the profile data associated with the authenticated user.
        /// </summary>
        /// <param name="emailId">A username is a name or email that uniquely identifies a user.</param>
        /// <param name="password">A password is a string of characters used for authenticating a user.</param>
        public RaasUserprofile AuthenticateUser(string emailId, string password)
        {
            _valuesToCheck = new ArrayList {emailId, password};
            _validate.Validate(_valuesToCheck, "Authenticate User");

            var getRequest = new HttpRequestParameter { { "username", emailId }, { "password", password } };

            var response = Get(_object, getRequest);

            return response.Deserialize<RaasUserprofile>();
        }
Example #14
0
        /// <summary>
        /// 配置请求消息
        /// </summary>
        /// <param name="request">Http请求参数</param>
        /// <returns></returns>
        public static HttpRequestMessage ConfigureReqMsg(HttpRequestParameter request)
        {
            var reqMsg = new HttpRequestMessage();

            reqMsg.RequestUri = string.IsNullOrWhiteSpace(request.AddressUrl)
                ? request.Uri
                : new Uri(request.AddressUrl);
            reqMsg.Method = new HttpMethod(request.Method.ToString().ToUpper());
            ConfigReqContent(reqMsg, request);//配置内容
            return(reqMsg);
        }
Example #15
0
        /// <summary>
        /// The Message API is used to post messages to the user’s contacts. After using the Contact API, you can send messages to the retrieved contacts.
        /// </summary>
        /// <param name="token">A valid session token,which is fetch from Access Token API.</param>
        /// <returns></returns>
        public string ExecuteAPI(Guid token)
        {
            string url = string.Format(Constants.APIRootDomain + Endpoint, token);

            HttpRequestParameter httprequestparameter = new HttpRequestParameter();
            httprequestparameter.Add("to", _To);
            httprequestparameter.Add("subject", _Subject);
            httprequestparameter.Add("message", _Message);

            return client.Request(url + "&" + httprequestparameter.ToString(), null, HttpMethod.POST);
        }
Example #16
0
        static void Main(string[] args)
        {
            IHttpProvider httpProvider = new HttpProvider();

            // 1. 模拟一个Get请求方式
            //HttpResponseParameter responseParameter1 = httpProvider.Excute(new HttpRequestParameter
            //{
            //    Url = "http://www.baidu.com",
            //    IsPost = false,
            //    Encoding = Encoding.UTF8
            //    //Cookie = new HttpCookieType() 如果需要Cookie
            //});
            //System.Console.WriteLine(responseParameter1.Body);

            // 2. 模拟一个Post请求方式(例:登录)
            //IDictionary<string, string> postData = new Dictionary<string, string>();
            //postData.Add("userName", "登录用户名");
            //postData.Add("userPwd", "用户名密码");
            //HttpResponseParameter responseParameter2 = httpProvider.Excute(new HttpRequestParameter
            //{
            //    Url = "你的登录url",
            //    IsPost = true,
            //    Encoding = Encoding.UTF8,
            //    Parameters = postData
            //});
            //System.Console.WriteLine(responseParameter2.Body);

            // 1. 模拟一个Get请求方式
            //http://lbfjapi.wsdict.com:8000/xpapi.ashx?method=xpshop.trades.sold.get&page_no=1&page_size=100

            //3.模拟一个Get请求方式  带参数
            IDictionary <string, string> postData = new Dictionary <string, string>();

            postData.Add("userName", "登录用户名");
            postData.Add("userPwd", "用户名密码");

            HttpRequestParameter HttpReq = new HttpRequestParameter
            {
                //Url = "http://www.baidu.com",
                Url        = "http://lbfjapi.wsdict.com:8000/xpapi.ashx?method=xpshop.shipping.type.get",
                IsPost     = false,
                Encoding   = Encoding.UTF8,
                Parameters = postData
                             //Cookie = new HttpCookieType() 如果需要Cookie
            };

            System.Console.WriteLine("请求数据为:" + HttpReq.ToString());
            HttpResponseParameter responseParameter3 = httpProvider.Excute(HttpReq);

            System.Console.WriteLine(responseParameter3.Body);

            System.Console.ReadLine();
        }
Example #17
0
        /// <summary>
        /// The Message API is used to post messages to the user’s contacts. After using the Contact API, you can send messages to the retrieved contacts.
        /// </summary>
        /// <param name="token">A valid session token,which is fetch from Access Token API.</param>
        /// <returns></returns>
        public string ExecuteAPI(Guid token)
        {
            string url = string.Format(Constants.APIRootDomain + Endpoint, token);

            HttpRequestParameter httprequestparameter = new HttpRequestParameter();

            httprequestparameter.Add("to", _To);
            httprequestparameter.Add("subject", _Subject);
            httprequestparameter.Add("message", _Message);

            return(client.Request(url + "&" + httprequestparameter.ToString(), null, HttpMethod.POST));
        }
        /// <summary>
        /// This method is used to check the presence of a Custom Object for the specified account ID(UID)
        /// </summary>
        /// <param name="accountId">The identifier for each user account, it may have multiple IDs(identifier for each social platform) attached with</param>
        /// <param name="objectId">LoginRadius Custom Object Id.</param>
        /// <returns></returns>
        public LoginRadiusCustomObjectCheckResponse CheckCustomObject(string accountId, string objectId)
        {
            _valuesToCheck = new ArrayList {accountId, objectId};
            _validate.Validate(_valuesToCheck, "Check Custom Object");
            var getRequest = new HttpRequestParameter
            {
                {"objectid", objectId},{"accountid",accountId}
            };

            var response = Get(_object.ChildObject("check"), getRequest);
            return response.Deserialize<LoginRadiusCustomObjectCheckResponse>();
        }
        /// <summary>
        /// Represents a method is used to check username exists or not on your site.
        /// </summary>
        /// <param name="username">Username to be check</param>
        public LoginRadiusEmailResponse CheckAccountUsername(string username)
        {
            _valuesToCheck = new ArrayList {username};
            _validate.Validate(_valuesToCheck, "Check Account Username");
            var getRequest = new HttpRequestParameter
            {
                {"username", username}
            };

            var response = Get(new LoginRadiusObject("user").ChildObject("checkusername"), getRequest);
            return response.Deserialize<LoginRadiusEmailResponse>();
        }
Example #20
0
        /// <summary>
        /// 设置请求Cookie
        /// </summary>
        /// <param name="request">HttpWebRequest对象</param>
        /// <param name="requestParameter">请求参数对象</param>
        private static void SetCookie(HttpWebRequest request, HttpRequestParameter requestParameter)
        {
            request.CookieContainer = new CookieContainer();
            if (requestParameter.Cookie != null && !string.IsNullOrEmpty(requestParameter.Cookie.Cookie))
            {
                request.Headers[HttpRequestHeader.Cookie] = requestParameter.Cookie.Cookie;
            }

            if (requestParameter.Cookie != null && requestParameter.Cookie.Cookies != null && requestParameter.Cookie.Cookies.Count > 0)
            {
                request.CookieContainer.Add(requestParameter.Cookie.Cookies);
            }
        }
Example #21
0
        /// <summary>
        /// Represents a method which is used to create Raas(Traditional) user profile of a social account.
        /// </summary>
        /// <param name="accountId">An account id is set of unique numerics and characters that uniquely identifies a user's account.</param>
        /// <param name="emailId">email address.</param>
        ///  <param name="password">A password is a string of characters used for authenticating a user or user password to be set.</param>
        public LoginRadiusPostResponse CreateRaaSProfile(string accountId, string emailId,string password)
        {
            _validate.Validate(_valuesToCheck = new ArrayList() { accountId, emailId, password }, "RaaS Profile");
            var postRequest = new HttpRequestParameter
            {
                { "accountid", accountId},
                { "emailid", emailId},
                { "password", password }
            };

            var response = Post(_object.ChildObject("profile"), postRequest);
            return response.Deserialize<LoginRadiusPostResponse>();
        }
        /// <summary>
        /// Method  is used to retrieve all of the Custom objects based on the Object Id.
        /// </summary>
        /// <param name="objectId">LoginRadius Custom Object Id.</param>
        /// <param name="cursor">Cursor or indexvalue value in case the data is large.</param>
        public List<CustomObjectResponse> GetAllCustomObject(string objectId, string cursor)
        {
            _valuesToCheck = new ArrayList {objectId, cursor};
            _validate.Validate(_valuesToCheck, "Get All Custom Object");
            var getRequest = new HttpRequestParameter
            {
                {"objectid", objectId},
                {"cursor", cursor}
            };

            var response = Get(_object, getRequest);
            return response.Deserialize<List<CustomObjectResponse>>();
        }
Example #23
0
        /// <summary>
        /// The Message API is used to post messages to the user’s contacts. After using the Contact API, you can send messages to the retrieved contacts.
        /// </summary>
        /// <param name="token">A valid session token,which is fetch from Access Token API.</param>
        /// <returns></returns>
        public string ExecuteApi(Guid token)
        {
            var url = string.Format(Constants.ApiRootDomain + Endpoint, token);

            var httprequestparameter = new HttpRequestParameter
            {
                {"to", _to},
                {"subject", _subject},
                {"message", _message}
            };

            return _client.Request(url + "&" + httprequestparameter, null, HttpMethod.POST);
        }
Example #24
0
        /// <summary>
        /// Represents a method which is used to remove the link between a users account and the specified provider’s user account.
        /// </summary>
        /// <param name="accountId">An account id is set of unique numerics and characters that uniquely identifies a user's account.</param>
        /// <param name="provider">A supported social provider in lower case which is to be unlinked.</param>
        ///  <param name="providerId">The ID of the social provider.</param>
        public LoginRadiusPostResponse UnlinkAccount(string accountId, string provider, string providerId)
        {
            _validate.Validate(_valuesToCheck = new ArrayList() { accountId, provider, providerId }, "UnlinkAccount");
            var postRequest = new HttpRequestParameter
            {
                { "accountid", accountId},
                { "provider", provider },
                { "providerid", providerId }
            };

            var response = Post(_object.ChildObject("unlink"), postRequest);

            return response.Deserialize<LoginRadiusPostResponse>();
        }
 /// <summary>
 /// This API is used to query the aggregation data from your LoginRadius cloud storage.
 /// </summary>
 /// <param name="from">From Date in format of (mm/dd/yyyy).</param>
 /// <param name="to">To Date in format of (mm/dd/yyyy).</param>
 /// <param name="firstDatapoint">Aggregation Field, supported are: os, browser, device, country, city, provider, emailType, friendsCount </param>
 /// <param name="statsType">Type of users should apply to i.e. NewUser, ActiveUser, Login</param>
 /// <returns></returns>
 public LoginRadiusQueryDataModel GetQueryAggregationData(string from, string to, string firstDatapoint, string statsType)
 {
     _validate.Validate(_valuesToCheck = new ArrayList() { from,to,firstDatapoint,statsType }, "Get Hash Password");
     var getRequest=new HttpRequestParameter
     {
         {"from",from},{"to",to}
     };
     var postRequest = new HttpRequestParameter
     {
         {"firstDatapoint", firstDatapoint},
         {"statsType", statsType}
     };
     var response = Post(new LoginRadiusObject("insights"), getRequest, postRequest);
     return response.Deserialize<LoginRadiusQueryDataModel>();
 }
Example #26
0
        /// <summary>
        /// The Status API is used to update the status on the user’s wall.
        /// </summary>
        /// <param name="token">A valid session token,which is fetch from Access Token API.</param>
        /// <returns></returns>
        public string ExecuteAPI(Guid token)
        {
            string url = string.Format(Constants.APIRootDomain + Endpoint, token);

            HttpRequestParameter httprequestparameter = new HttpRequestParameter();

            httprequestparameter.Add("title", _title);
            httprequestparameter.Add("url", _url);
            httprequestparameter.Add("imageurl", _imageurl);
            httprequestparameter.Add("status", _status);
            httprequestparameter.Add("caption", _caption);
            httprequestparameter.Add("description", _description);

            return(client.Request(url + "&" + httprequestparameter.ToString(), null, HttpMethod.POST));
        }
 /// <summary>
 /// This API allows you to query your LoginRadius Cloud Storage and retrieve up to 20 user records.
 /// </summary>
 /// <param name="select"> Fields included in the Query, default all fields, Optional: can be null or empty string</param>
 /// <param name="from">LoginRadius Table that details are being retrieved from, for now users only supported </param>
 /// <param name="where">Filter for data based on condition,Optional: can be null or empty string </param>
 /// <param name="orderBy">Determines ascending order of returned data,Optional: can be null or empty string</param>
 /// <param name="skip">Ignores the specified amount of values used to page through responses, value must be positive and default value is 0, Optional: can be null or empty string</param>
 /// <param name="limit">Determines size of dataset returned. default value is 20 and max value is 20, Optional: can be null or empty string</param>
 /// <returns></returns>
 public List<LoginRadiusIdentityModel> GetUserList(string select, string from, string where, string orderBy, string skip,
     string limit)
 {
     var postRequest = new HttpRequestParameter
     {
         {"From", string.IsNullOrWhiteSpace(from)?"users":from}
     };
     if (!string.IsNullOrWhiteSpace(select)) { postRequest.Add("Select",select); }
     if (!string.IsNullOrWhiteSpace(where)) { postRequest.Add("Where", where); }
     if (!string.IsNullOrWhiteSpace(orderBy)) { postRequest.Add("OrderBy", orderBy); }
     if (!string.IsNullOrWhiteSpace(skip)) { postRequest.Add("Skip", skip); }
     if (!string.IsNullOrWhiteSpace(limit)) { postRequest.Add("Limit", limit); }
     var response = Post(_object, postRequest);
     return response.Deserialize<List<LoginRadiusIdentityModel>>();
 }
Example #28
0
        public virtual string DoRequest_Content(string Url, bool IsPost, KeyValuePair <string, string> sign)
        {
            var                  respContent = string.Empty;
            HttpClient           client      = new HttpClient();
            HttpRequestParameter parms       = new HttpRequestParameter()
            {
                IsPost       = IsPost,
                Encoding     = System.Text.Encoding.UTF8,
                Url          = Url,
                ContentInput = this.CreatePostData(sign)
            };
            var rsp = client.Excute(parms);

            respContent = rsp.Body;
            return(respContent);
        }
 /// <summary>
 /// Method is used to remove the specified Custom Object based on the account Id(UID).
 /// </summary>
 /// <param name="objectId">LoginRadius Custom Object Id.</param>
 ///  <param name="accountId">Account Id is a uniquely generated string used for determination of a user account.</param>
 /// <param name="isblock"></param>
 public LoginRadiusPostResponse DeleteCustomObject(string accountId, string objectId, bool isblock)
 {
     _valuesToCheck = new ArrayList {objectId, accountId};
     _validate.Validate(_valuesToCheck, "Delete Custom Object");
     var getRequest = new HttpRequestParameter
     {
         {"accountid", accountId},
         {"objectid", objectId}
     };
     var loginRadiusBlockUnblockModel = new LoginRadiusBlockUnblockModel
     {
         IsBlock = isblock
     };
     var response = Post(_object.ChildObject("status"), getRequest, loginRadiusBlockUnblockModel.Serialize());
     return response.Deserialize<LoginRadiusPostResponse>();
 }
 /// <summary>
 /// Method to change a user password.
 /// </summary>
 /// <param name="userid">A userid is set of unique numerics and characters that uniquely identifies a user.</param>
 ///  <param name="oldPassword">Old Password is the current passowrd of a user or password is to be changed.</param>
 ///  <param name="newPassword">A new unique set of characters and numbers which is to be used as a passsword.</param>
 public LoginRadiusPostResponse ChangePassword(string userid, string oldPassword, string newPassword)
 {
     _valuesToCheck = new ArrayList {userid, newPassword, oldPassword};
     _validate.Validate(_valuesToCheck, "ChangePassword");
     var postRequest = new HttpRequestParameter
     {
         {"oldpassword", oldPassword},
         {"newpassword", newPassword}
     };
     var getRequest = new HttpRequestParameter
     {
         {"userid", userid}
     };
     var response = Post(_object.ChildObject("password"), getRequest, postRequest);
     return response.Deserialize<LoginRadiusPostResponse>();
 }
Example #31
0
        public virtual string DoRequest(string Url, bool IsPost, KeyValuePair <string, string> sign)
        {
            var                  respContent = string.Empty;
            HttpClient           client      = new HttpClient();
            HttpRequestParameter parms       = new HttpRequestParameter()
            {
                IsPost     = IsPost,
                Encoding   = System.Text.Encoding.UTF8,
                Url        = Url,
                Parameters = CommitParms.AddOrReplace(sign.Key, sign.Value)
            };
            var rsp = client.Excute(parms);

            respContent = rsp.Body;
            return(respContent);
        }
        protected string Get(LoginRadiusObject @object, HttpRequestParameter parameter)
        {
            if (parameter == null)
            {
                parameter = _commHttpRequestParameter;
            }
            else
            {
                foreach (var par in _commHttpRequestParameter)
                {
                    parameter.Add(par.Key, par.Value);
                }
            }

            var response = _httpClient.HttpGet(GetEndpoint(@object.ObjectName), parameter);
            return response.ResponseContent;
        }
        /// <summary>
        /// Method is used for changing user name by account Id.
        /// </summary>
        /// <param name="accountId">the identifier for each user account.</param>
        ///  <param name="currentusername">Current Username or username to be changed.</param>
        /// <param name="newusername">New username</param>
        public LoginRadiusPostResponse ChangeAccountUsername(string accountId, string currentusername,string newusername)
        {
            _valuesToCheck = new ArrayList {accountId, currentusername, newusername};
            _validate.Validate(_valuesToCheck, "Change Account Username");
            var postRequest = new HttpRequestParameter
            {
                {"oldusername", currentusername},
                {"newusername",newusername }
            };
            var getRequest = new HttpRequestParameter
            {
                {"accountid", accountId}
            };

            var response = Post(_object.ChildObject("changeusername"), getRequest, postRequest);
            return response.Deserialize<LoginRadiusPostResponse>();
        }
        protected string Post(LoginRadiusObject @object, HttpRequestParameter getParams, string postParams)
        {
            if (getParams == null)
            {
                getParams = _commHttpRequestParameter;
            }
            else
            {
                foreach (var par in _commHttpRequestParameter)
                {
                    getParams.Add(par.Key, par.Value);
                }
            }

            var response = _httpClient.HttpPostJson(GetEndpoint(@object.ObjectName), getParams, postParams);
            return response.ResponseContent;
        }
Example #35
0
        /// <summary>
        /// 设置请求参数
        /// </summary>
        /// <param name="request">HttpWebRequest对象</param>
        /// <param name="requestParameter">请求参数对象</param>
        private static void SetParameter(HttpWebRequest request, HttpRequestParameter requestParameter)
        {
            if (requestParameter.RequestType == RequestType.GET)
            {
                if (request != null)
                {
                    return;
                }

                //Get 拼接URL参数

                if (requestParameter.Parameters == null || requestParameter.Parameters.Count <= 0)
                {
                    return;
                }

                StringBuilder requestParamsBuilder = new StringBuilder();
                foreach (KeyValuePair <string, string> keyValuePair in requestParameter.Parameters)
                {
                    requestParamsBuilder.AppendFormat("{0}={1}&", keyValuePair.Key, keyValuePair.Value);
                }

                requestParameter.Uri = string.Concat(requestParameter.Uri, $"?{requestParamsBuilder.ToString().TrimEnd('&')}");
            }
            else if (request != null)
            {
                //Post 设置请求参数

                string requestData;
                if (requestParameter.Parameters == null || requestParameter.Parameters.Count <= 0)
                {
                    requestData = "{}";
                }
                else
                {
                    requestData = JsonHelper.SerializeObject(requestParameter.Parameters);
                }

                byte[] bytePosts = requestParameter.Encoding.GetBytes(requestData);
                request.ContentLength = bytePosts.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytePosts, 0, bytePosts.Length);
                }
            }
        }
Example #36
0
 /// <summary>
 /// 写入 Form 的内容值【非文件参数+文件头+文件参数(内部完成)+请求结束符】
 /// </summary>
 /// <param name="memory">流</param>
 /// <param name="request">Http请求参数</param>
 /// <param name="boundary">请求分隔符</param>
 private static void WriteMultipartFormData(Stream memory, HttpRequestParameter request, string boundary)
 {
     foreach (var param in request.FormParameters)
     {
         WriteStringTo(memory, GetMultipartFormData(param, boundary));
     }
     foreach (var param in request.FileParameters)
     {
         // 文件头
         WriteStringTo(memory, GetMultipartFileHeader(param, boundary));
         // 文件内容
         param.Writer(memory);
         // 文件结尾
         WriteStringTo(memory, _lineBreak);
     }
     // 写入整个请求的底部信息
     WriteStringTo(memory, GetMultipartFooter(boundary));
 }
Example #37
0
        /// <summary>
        /// 执行请求
        /// </summary>
        /// <param name="requestParameter">请求报文</param>
        /// <returns>响应报文</returns>
        public static HttpResponseParameter Excute(HttpRequestParameter requestParameter)
        {
            SetParameter(null, requestParameter);
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(requestParameter.Uri, UriKind.RelativeOrAbsolute));

            SetHeader(webRequest, requestParameter);
            SetCookie(webRequest, requestParameter);

            // https请求设置
            if (Regex.IsMatch(requestParameter.Uri, "^https://"))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
            }

            SetParameter(webRequest, requestParameter);
            return(SetResponse(webRequest, requestParameter));
        }
        public static HttpCookieType ShowRandCode(HttpCookieType sessionCookie, Image viefCode)
        {
            var SessionCookie = new HttpCookieType();

            SessionCookie = sessionCookie;
            //GetSessionCookie();
            var request = new HttpRequestParameter();

            request.Url = string.Format(_12306UrlConfig.RandCodeUrl,
                                        DateTime.Now.ToString("yyyyMMddHHmmsss"));
            request.ResponseEnum = HttpResponseEnum.Stream;
            request.Cookie       = sessionCookie;
            request.StreamAction = x =>
            {
                MemoryStream ms     = new MemoryStream();
                byte[]       buffer = new byte[1024];
                while (true)
                {
                    int sz = x.Read(buffer, 0, buffer.Length);
                    if (sz == 0)
                    {
                        break;
                    }
                    ms.Write(buffer, 0, sz);
                }
                ms.Position = 0;

                BitmapImage bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(ms.ToArray());
                bmp.EndInit();

                viefCode.Source = bmp;

                ms.Close();
            };

            var response = new HttpProvider().Excute(request);

            SessionCookie.CookieCollection.Add(response.Cookie.CookieCollection);
            SessionCookie.CookieString = SessionCookie.CookieString + "," + response.Cookie.CookieString;

            return(sessionCookie);
        }
        void ShowCode()
        {
            GetLoginSessionCookie();

            var request = new HttpRequestParameter();

            request.Url = string.Format("https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&{0}",
                                        DateTime.Now.ToString("yyyyMMddHHmmsss"));
            request.ResponseEnum = HttpResponseEnum.Stream;
            request.Cookie       = SessionCookie;
            request.StreamAction = x =>
            {
                MemoryStream ms     = new MemoryStream();
                byte[]       buffer = new byte[1024];
                while (true)
                {
                    int sz = x.Read(buffer, 0, buffer.Length);
                    if (sz == 0)
                    {
                        break;
                    }
                    ms.Write(buffer, 0, sz);
                }
                ms.Position = 0;

                BitmapImage bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(ms.ToArray());
                bmp.EndInit();

                viefCode.Source = bmp;

                ms.Close();
            };

            var response = HttpProvider.Excute(request);

            SessionCookie.CookieCollection.Add(response.Cookie.CookieCollection);
            SessionCookie.CookieString = SessionCookie.CookieString + "," + response.Cookie.CookieString;
        }
Example #40
0
        /// <summary>
        /// 设置返回结果
        /// </summary>
        /// <param name="request">HttpWebRequest对象</param>
        /// <param name="requestParameter">请求参数对象</param>
        /// <returns>响应对象</returns>
        private static HttpResponseParameter SetResponse(HttpWebRequest request, HttpRequestParameter requestParameter)
        {
            HttpResponseParameter responseParameter = new HttpResponseParameter();

            using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
            {
                responseParameter.Uri        = webResponse.ResponseUri;
                responseParameter.StatusCode = webResponse.StatusCode;
                responseParameter.Cookie     = new HttpCookieType
                {
                    Cookies = webResponse.Cookies,
                    Cookie  = webResponse.Headers["Set-Cookie"]
                };

                using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), requestParameter.Encoding))
                {
                    responseParameter.Body = reader.ReadToEnd();
                }
            }

            return(responseParameter);
        }
Example #41
0
        /// <summary>
        /// 获取请求的内容信息(非文件上传请求)
        /// eg:正常 get / post 请求
        /// </summary>
        /// <param name="request">Http请求参数</param>
        /// <returns></returns>
        private static string GetNormalFormData(HttpRequestParameter request)
        {
            var formString = new StringBuilder();

            foreach (var parm in request.FormParameters)
            {
                if (formString.Length > 1)
                {
                    formString.Append("&");
                }
                formString.AppendFormat(parm.ToString());
            }
            if (!string.IsNullOrWhiteSpace(request.CustomBody))
            {
                if (formString.Length > 1)
                {
                    formString.Append("&");
                }
                formString.Append(request.CustomBody);
            }
            return(formString.ToString());
        }
Example #42
0
        /// <summary>
        /// 显示验证码
        /// </summary>
        void ViewCode()
        {
            GetLoginSessionCookie();

            var request = new HttpRequestParameter();

            request.Url = string.Format("http://passport.jikexueyuan.com/sso/verify?t={0}",
                                        DateTime.Now.ToString("yyyyMMddHHmmsss"));
            request.ResponseEnum = HttpResponseEnum.Stream;
            request.Cookie       = SessionCookie;
            request.StreamAction = x =>
            {
                MemoryStream ms     = new MemoryStream();
                byte[]       buffer = new byte[1024];
                while (true)
                {
                    int sz = x.Read(buffer, 0, buffer.Length);
                    if (sz == 0)
                    {
                        break;
                    }
                    ms.Write(buffer, 0, sz);
                }
                ms.Position = 0;

                BitmapImage bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(ms.ToArray());
                bmp.EndInit();

                VerifyCode.Source = bmp;

                ms.Close();
            };

            HttpProvider.Excute(request);
        }
Example #43
0
 /// <summary>
 /// 执行请求方法
 /// </summary>
 /// <param name="request">Http请求参数</param>
 /// <param name="completionOption">Http完成操作</param>
 /// <param name="client">Http请求客户端</param>
 /// <returns></returns>
 public static Task <HttpResponseMessage> SendReq(this HttpRequestParameter request,
                                                  HttpCompletionOption completionOption, HttpClient client = null)
 {
     return(SendReq(request, completionOption, CancellationToken.None, client));
 }
 /// <summary>
 /// Method which is used to deletes the Users account and allows them to re-register for a new account.
 /// </summary>
 /// <param name="accountId">An account id is set of unique numerics and characters that uniquely identifies a user's account or the identifier for each user account, it may have multiple IDs.</param>
 public LoginRadiusPostResponse DeleteAccount(string accountId)
 {
     _valuesToCheck = new ArrayList {accountId};
     _validate.Validate(_valuesToCheck, "DeleteAccount");
     var getRequest = new HttpRequestParameter
     {
         { "accountid", accountId }
     };
     var response = Get(_object.ChildObject("delete"), getRequest);
     return response.Deserialize<LoginRadiusPostResponse>();
 }
Example #45
0
 /// <summary>
 /// 设置请求头
 /// </summary>
 /// <param name="request">HttpWebRequest对象</param>
 /// <param name="requestParameter">请求参数对象</param>
 private static void SetHeader(HttpWebRequest request, HttpRequestParameter requestParameter)
 {
     request.Method      = requestParameter.RequestType.ToString();
     request.ContentType = "application/json";
 }
Example #46
0
 public HttpResponseParameter ExcuteWithStringConten(HttpRequestParameter requestParameter)
 {
     return(HttpUtil.ExcuteWithStringContent(requestParameter));
 }
        /// <summary>
        /// Method  is used to add or remove additional emails to a user's account.
        /// </summary>
        /// <param name="accountid">Account Id is a uniquely generated string used for determination of a user account.</param>
        /// <param name="action">Add or remove.</param>
        /// <param name="emailId">Email address.</param>
        /// <param name="emailType">Email Type like "Business" or Personal.</param>
        public LoginRadiusPostResponse UserEmailAddOrRemove(string accountid, string action, string emailId, string emailType)
        {
            _valuesToCheck = new ArrayList {accountid, emailType, action, emailId};
            _validate.Validate(_valuesToCheck, "User Email Add or Remove");
            var getRequest = new HttpRequestParameter
            {
                {"accountid", accountid},
                {"action", action}
            };
            var postRequest = new HttpRequestParameter
            {
                {"EmailId", emailId},
                {"EmailType", emailType}
            };

            var response = Post(_object.ChildObject("email"), getRequest, postRequest);
            return response.Deserialize<LoginRadiusPostResponse>();
        }
        /// <summary>
        /// Method which is used to block or unblock a Users account. It prevents them from logging in our registering for a new account.
        /// </summary>
        /// <param name="accountId">An account id is set of unique numerics and characters that uniquely identifies a user's account or the identifier for each user account.</param>
        /// <param name="isBlock">True or False , defines the status to be set. </param>
        public LoginRadiusPostResponse SetAccountStatus(string accountId, bool isBlock)
        {
            _valuesToCheck = new ArrayList {accountId, isBlock};
            _validate.Validate(_valuesToCheck, "SetAccountStatus");
            var getRequest = new HttpRequestParameter
            {
                { "accountid", accountId }
            };
            LoginRadiusBlockUnblockModel loginRadiusBlockUnblockModel = new LoginRadiusBlockUnblockModel
            {
                IsBlock = isBlock
            };
            var json = new JavaScriptSerializer().Serialize(loginRadiusBlockUnblockModel);
            var response = Post(_object.ChildObject("status"), getRequest, json);

            return response.Deserialize<LoginRadiusPostResponse>();
        }
        /// <summary>
        /// Method is used to set a new password for the specified account. It is meant to be used as an admin feature or post authentication.
        /// </summary>
        /// <param name="accountId">the identifier for each user account.</param>
        ///  <param name="password">A password is a string of characters used for authenticating a user or account password to be set.</param>
        public LoginRadiusPostResponse SetAccountPassword(string accountId, string password)
        {
            _valuesToCheck = new ArrayList {accountId, password};
            _validate.Validate(_valuesToCheck, "Set Account Password");
            var postRequest = new HttpRequestParameter
            {
                {"password", password}
            };
            var getRequest = new HttpRequestParameter
            {
                {"action", "setpassword"},
                {"accountid", accountId}
            };

            var response = Post(_object.ChildObject("password"), getRequest, postRequest);
            return response.Deserialize<LoginRadiusPostResponse>();
        }
 /// <summary>
 /// This method is used to generate an email-token that can be sent out to a user in a link in order to verify their email.
 /// </summary>
 /// <param name="emailId">User's email address</param>
 /// <param name="link">Verification Url link address</param>
 /// <param name="template">Verification Email Template,Optional</param>
 /// <returns></returns>
 public LoginRadiusEmailVerificationToken ResendUserVerificationEmail(string emailId, string link, string template)
 {
     _valuesToCheck = new ArrayList {emailId, link};
     _validate.Validate(_valuesToCheck, "Resend User Verification Email");
     var getRequest = new HttpRequestParameter
     {
         { "emailid", emailId },{"link",link}
     };
     if (!string.IsNullOrWhiteSpace(template))
     {
         getRequest.Add("template", template);
     }
     var response = Get(_object.ChildObject("verificationemail"), getRequest);
     return response.Deserialize<LoginRadiusEmailVerificationToken>();
 }
Example #51
0
 /// <summary>
 /// 执行请求方法
 /// </summary>
 /// <param name="request">Http请求参数</param>
 /// <param name="completionOption">Http完成操作</param>
 /// <param name="cancellationToken">取消操作通知</param>
 /// <param name="client">Http请求客户端</param>
 /// <returns></returns>
 public static Task <HttpResponseMessage> SendReq(this HttpRequestParameter request,
                                                  HttpCompletionOption completionOption, CancellationToken cancellationToken, HttpClient client = null)
 {
     return((client ?? GetDefaultClient()).SendReq(request, completionOption, cancellationToken));
 }
Example #52
0
 public HttpResponseParameter Excute(HttpRequestParameter requestParameter)
 {
     return(HttpUtil.Excute(requestParameter));
 }
Example #53
0
 /// <summary>
 /// 执行请求方法
 /// </summary>
 /// <param name="client">Http客户端</param>
 /// <param name="request">Http请求参数</param>
 /// <returns></returns>
 public static Task <HttpResponseMessage> SendReq(this HttpClient client, HttpRequestParameter request)
 {
     return(SendReq(client, request, HttpCompletionOption.ResponseContentRead, CancellationToken.None));
 }