/// <summary> /// Return Response Code /// </summary> /// <param name="url"></param> /// <param name="httpType"></param> /// <returns></returns> public int GetResponseCode(string url, HttpType httpType) { Log.Debug("{httpType} ::: {url}", url, httpType); var request = (HttpWebRequest)WebRequest.Create(url); request.Method = httpType.ToString().ToUpper(); HttpWebResponse response; try { if (httpType == HttpType.Post) { var encoding = new ASCIIEncoding(); var bytesToWrite = encoding.GetBytes(string.Empty); request.ContentLength = bytesToWrite.Length; } response = (HttpWebResponse)request.GetResponse(); } catch { return((int)Constants.HttpStatusCode.NotFound); } var status = response.StatusCode; return((int)status); }
/// <summary> /// Return Response Code /// </summary> /// <param name="url"></param> /// <param name="httpType"></param> /// <returns></returns> public int GetResponseCode(string url, HttpType httpType) { Log.Debug("{httpType} ::: {url}", url, httpType); var request = (HttpWebRequest) WebRequest.Create(url); request.Method = httpType.ToString().ToUpper(); HttpWebResponse response; try { if (httpType == HttpType.Post) { var encoding = new ASCIIEncoding(); var bytesToWrite = encoding.GetBytes(string.Empty); request.ContentLength = bytesToWrite.Length; } response = (HttpWebResponse) request.GetResponse(); } catch { return (int) Constants.HttpStatusCode.NotFound; } var status = response.StatusCode; return (int) status; }
public HttpAction(HttpType http) { _Http = http; CreateMethodType(); }
protected override void CustomValidate(Customer entity, HttpType http) { //base.Validate(entity); //Nhận mã từ base if (entity is Customer) //Ép kiểu { var customer = entity as Customer; //CustomerException.CheckValidEmail(customer.Email); //Kiểm tra xem customerCode đã tồn tại chưa (phía server) (duplicate) var isCustomerCodeExists = _customerRepository.CheckDuplicateCustomerCode(customer.CustomerCode, customer.CustomerId, http); if (isCustomerCodeExists == true) { throw new CustomerException(Properties.Resources.Customer_Code_Exists_msg); } ////Kiểm tra email đã tồn tại chưa (phía server) //var isEmailExists = _customerRepository.CheckDuplicateEmail(customer.Email); //if (isEmailExists == true) //{ // throw new CustomerException("Email đã tồn tại trên hệ thống!."); //} ////Kiểm tra số điện thoại đã tồn tại chưa (phía server) //var isPhoneNumberExists = _customerRepository.CheckDuplicatePhoneNumber(customer.PhoneNumber); //if (isPhoneNumberExists == true) //{ // throw new CustomerException("Số điện thoại đã tồn tại trên hệ thống!."); //} } }
private string GetExec(HttpType type, string url, object payload) { if (payload != null) { url += ToQueryString(payload); } return(Exec(type, url).Result); }
/// <summary> /// 注:需要加密 /// post方式只能发送2进制 /// get只能发字符串 /// </summary> /// <typeparam name="T">接收消息是需要转换的类型,BaseData子类型</typeparam> /// <param name="protocol"></param> /// <param name="jsonToSend"></param> /// <param name="httpType">发送格式</param> /// <param name="receiveType">接收数据类型enum DataType</param> /// <param name="callback"></param> public void SendHttpMessage <T>(int protocol, object jsonToSend, HttpType httpType, System.Action <int, int, T> callback = null) where T : BaseData { HttpMessage <T> t_msg = GetFreeMessage <T>() as HttpMessage <T>; t_msg.SendHttpMessage(protocol, jsonToSend, httpType, callback); t_msg.onReceiveError = OnReceiveError; t_msg.onReceiveOver = OnReceiveOver; m_httpMessageList.Add(t_msg); }
//Validate dữ liệu khi post lên database protected override void CustomValidate(Employee entity, HttpType http) { if (entity is Employee) { var employee = entity as Employee; //Kiểm tra mã nhân viên đã tồn tại chưa var isEmployeeCodeExists = _employeeRepository.CheckDuplicateEmployeeCode(employee.EmployeeCode, employee.EmployeeId, http); if (isEmployeeCodeExists == true) { throw new CustomerException(Properties.Resources.Employee_Code_Exists_msg); } } }
/// <summary> /// Performs an asynchronous POST request to the Dinero API with the given binary body. /// </summary> /// <param name="dinero">An instance of the Dinero class. This is needed since it know about the user, the app and their credentials.</param> /// <param name="baseUri">The base URI to Dineo API. This is the URL without the path, but only the domain and API version.</param> /// <param name="requestParameters">Parameters to be used for generating the URL. Should contain the endpoint, the post body and any needed query parameters.</param> /// <param name="httpType">The type to determind if to use, get, post, delete or put</param> /// <param name="body">The body</param> internal async static Task<string> PerformAsync(Dinero dinero, Uri baseUri, Dictionary<string, string> requestParameters, HttpType httpType, byte[] body) { var url = BuildUri(dinero, baseUri, requestParameters).AbsoluteUri; var fileName = requestParameters[DineroApiParameterName.FileName]; using (var content = new MultipartFormDataContent("-------abcdefg1234")) { var byteContent = new ByteArrayContent(body); var fileExtension = Path.GetExtension(fileName); byteContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MimeTypeMap.GetMimeType(fileExtension)); content.Add(byteContent, MimeTypeMap.GetMimeTypeType(fileExtension), fileName); return await WorkAsync(dinero, httpType, url, content); } }
public static dynamic MakeRequests(string url, HttpType method, Dictionary <string, string> data) { HttpWebResponse response; if (Request(out response, url, method, data)) { var result = ReadResponse(response); response.Close(); return(response); } return(null); }
public static string MakeRequestsWithXmldata(string url, HttpType method, string data) { HttpWebResponse response; if (RequestWithXmldata(out response, url, method, data)) { var result = ReadResponse(response); response.Close(); return(response.ContentEncoding); } return(null); }
public Dictionary <string, string> ToReplacementDictionary(Dictionary <string, string> dct) { dct.Add("$aurelia_project_name$", AureliaProjectName); dct.Add("$aurelia_module_loader$", ModuleLoader.ToString()); dct.Add("$aurelia_http_type$", HttpType.ToString()); dct.Add("$aurelia_transpiler$", Transpiler.ToString()); dct.Add("$aurelia_minification$", Minification.ToString()); dct.Add("$aurelia_css_processing$", CSSProcessing.ToString()); dct.Add("$aurelia_unit_ruinner$", UnitTestRunner.ToString()); dct.Add("$aurelia_integration_testing$", IntegrationTesting.ToString()); dct.Add("$aurelia_install_after$", InstallAfter.ToString()); dct.Add("$aurelia_build_after$", BuildAfter.ToString()); return(dct); }
public void Release(bool destroy = false) { m_jsonToSend = null; m_httpType = HttpType.Post; m_result = 0; m_callback = null; onReceiveError = null; onReceiveOver = null; m_receiveMsg = null; if (destroy) { m_httpClient = null; } }
private async Task <string> Exec(HttpType type, string url, object payload = null) { HttpResponseMessage response; var content = payload != null ? new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json") : null; IncludeHeader(); switch (type) { case HttpType.Post: response = await _client.PostAsync(url, content); break; case HttpType.Get: response = await _client.GetAsync(url); break; case HttpType.Put: response = await _client.PutAsync(url, content); break; case HttpType.Delete: response = await _client.DeleteAsync(url); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } if (response.StatusCode == HttpStatusCode.NotFound) { throw new HttpRequestException($"\"{url}\" returning 404 not found"); } return(await ReadResponse(response)); }
/// <summary> /// Analyzes the Attributes on the current method and determines whether it has any ASP.NET MVC /// properties to make the method an HTTP REST Endpoint Method. If there is, returns which type. /// If there isn't, it returns HttpType.None. /// </summary> /// <returns>HttpType.None if no ASP.NET style attributes can be found on the function. Otherwise, /// the first HttpType that can be found.</returns> private HttpType GetHttpType() { HttpType http = HttpType.None; foreach (AttributeSyntax attributeSyntax in this.attributeSyntaxes) { string attributeName = attributeSyntax.Name.ToString(); if (attributeName.StartsWith("Http")) { if (Enum.TryParse(attributeName.Replace("Http", ""), out HttpType httpTemp)) { http = httpTemp; break; } } } return(http); }
/// <summary> /// /// </summary> /// <param name="protocol">协议</param> /// <param name="jsonToSend">数据对象</param> /// <param name="httpType">发送类型HttpType</param> /// <param name="callback"></param> public void SendHttpMessage(int protocol, object jsonToSend, HttpType httpType, System.Action <int, int, T> callback = null) { m_jsonToSend = jsonToSend; m_httpType = httpType; m_callback = callback; if (m_httpType == HttpType.Post) { SendMessage msg = new SendMessage(); msg.protocol = protocol; msg.data = m_jsonToSend; m_httpClient.PostAsync(m_ip, JsonToBytes(msg)); } else//HttpType.Get { m_httpClient.GetAsync(m_ip + PrefixProtocol + JsonToString(m_jsonToSend)); } }
public static bool Request(out HttpWebResponse response, string url, HttpType method, Dictionary <string, string> data) { response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToString(); if (data != null) { foreach (var i in data) { request.Headers.Set(i.Key, i.Value); } } response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { response = (HttpWebResponse)e.Response; } else { return(false); } } catch (Exception) { if (response != null) { response.Close(); } return(false); } return(true); }
/// <summary> /// Http通用请求(同步方式) /// </summary> /// <param name="url"></param> /// <param name="type"></param> /// <param name="inputData"></param> /// <param name="username">用户名</param> /// <param name="pwd">密码</param> /// <returns></returns> public static string HttpRequest(string url, HttpType type, string inputData = "", string username = "", string pwd = "") { switch (type) { case HttpType.PUT: return(Put(url, inputData, username, pwd)); case HttpType.GET: return(Get(url, username, pwd)); case HttpType.POST: return(Post(url, inputData, username, pwd)); case HttpType.DELETE: return(Delete(url, inputData, username, pwd)); default: break; } return(""); }
public static string httpRequest(string url, HttpType type, ContentType eContentType, string inputData = "") { switch (type) { case HttpType.PUT: return(_put(url, eContentType, inputData)); case HttpType.GET: return(_get(url, eContentType)); case HttpType.POST: return(_post(url, eContentType, inputData)); case HttpType.DELETE: return(_delete(url, eContentType, inputData)); default: break; } return(""); }
/// <summary> /// Check trùng mã nhân viên /// </summary> /// <param name="employeeCode"></param> /// <param name="employeeId"></param> /// <param name="http"></param> /// <returns>True: nếu trùng</returns> /// <returns>False: nếu không trùng</returns> public bool CheckDuplicateEmployeeCode(string employeeCode, Guid employeeId, HttpType http) { using (dbConnection = new MySqlConnection(connectionString)) { var sqlCommand = ""; DynamicParameters dynamicParameters = new DynamicParameters(); if (http == HttpType.POST) { sqlCommand = "Proc_CheckEmployeeCodeExist"; dynamicParameters.Add("EmployeeCode", employeeCode); } else { //Check trùng mã khách hàng sqlCommand = "Proc_CheckEmployeeCodeExistPut"; dynamicParameters.Add("EmployeeCode", employeeCode); dynamicParameters.Add("Id", employeeId); } var Exists = dbConnection.QueryFirstOrDefault <bool>(sqlCommand, param: dynamicParameters, commandType: CommandType.StoredProcedure); return(Exists); } }
/// <summary> /// 异步方式请求 /// </summary> /// <param name="url"></param> /// <param name="type"></param> /// <param name="inputData"></param> /// <param name="username">用户名</param> /// <param name="pwd">密码</param> public static void HttpRequestNoResult(string url, HttpType type, string inputData = "", string username = "", string pwd = "") { switch (type) { case HttpType.PUT: PutNoResult(url, inputData, username, pwd); break; case HttpType.GET: GetNoResult(url, username, pwd); break; case HttpType.POST: PostNoResult(url, inputData, username, pwd); break; case HttpType.DELETE: DeleteNoResult(url, inputData, username, pwd); break; default: break; } }
/// <summary> /// Kiểm tra dữ liệu, trả về exception nếu gặp lỗi /// </summary> /// <param name="entity"></param> /// <param name="http"></param> private void Validate(MISAEntity entity, HttpType http) { //Viết những đoạn mã validate chung giữa customer và customerGroup //Lấy ra tất cả property của class var properties = typeof(MISAEntity).GetProperties(); foreach (var property in properties) { //Lấy giá trị var propertyValue = property.GetValue(entity); ///Kiểm tra required field có null không, nếu có thì throw exception //Lấy ra property RequiredField var requiredProperties = property.GetCustomAttributes(typeof(RequiredField), true); if (requiredProperties.Length > 0) { //Kiểm tra nếu giá trị là null if (propertyValue == null) { propertyValue = ""; } //Kiểm tra nếu giá trị bị bỏ trống if (string.IsNullOrEmpty(propertyValue.ToString())) { var msgError = (requiredProperties[0] as RequiredField).MsgError; if (string.IsNullOrEmpty(msgError)) { msgError = $"Thông tin {property.Name} không được phép để trống"; } throw new CustomerException(msgError); } } ///Kiểm tra email field có đúng định dạng hay không, nếu có thì throw exception //Lấy ra property emailField var emailProperties = property.GetCustomAttributes(typeof(EmailField), true); if (emailProperties.Length > 0) { //Kiểm tra giá trị if (!Regex.IsMatch(propertyValue.ToString(), @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" /*Properties.Resources.Regex_email*/)) { var response = new { devMsg = Properties.Resources.Email_Invalid_msg, MISACode = Properties.Resources.MISACode }; throw new CustomerException(response.devMsg); } } ///Kiểm tra phoneNumberField có đúng định dạng hay không, nếu có thì throw exception //Lấy ra property phoneNumberField var phoneNumberProperties = property.GetCustomAttributes(typeof(PhoneNumberField), true); if (phoneNumberProperties.Length > 0) { //Kiểm tra giá trị if (!Regex.IsMatch(propertyValue.ToString(), @"^((\+0?1\s)?)\(?\d{3}\)?[\s.\s]\d{3}[\s.-]\d{4}$" /*Properties.Resources.Regex_phoneNumber*/)) { var response = new { devMsg = Properties.Resources.PhoneNumber_Invalid_msg, MISACode = Properties.Resources.MISACode }; throw new CustomerException(response.devMsg); } } ///Kiểm tra MaxLengthField không quá 20 kí tự, nếu quá thì throw exception //Lấy ra property MaxLengthField var maxLengthProperties = property.GetCustomAttributes(typeof(MaxLengthField), true); if (maxLengthProperties.Length > 0) { var maxLength = (maxLengthProperties[0] as MaxLengthField).MaxLength; if (propertyValue.ToString().Length > maxLength) { var msgError = (maxLengthProperties[0] as MaxLengthField).MsgError; if (string.IsNullOrEmpty(msgError)) { msgError = $"Thông tin {property.Name} không được quá {maxLength} kí tự"; } throw new CustomerException(msgError); } } } CustomValidate(entity, http); }
/// <summary> /// Performs an asynchronous request to the Dinero API. /// </summary> /// <param name="dinero">An instance of the Dinero class. This is needed since it know about the user, the app and their credentials.</param> /// <param name="baseUri">The base URI to Dineo API. This is the URL without the path, but only the domain and API version.</param> /// <param name="requestParameters">Parameters to be used for generating the URL. Should contain the endpoint and any needed query parameters.</param> /// <param name="httpType">The type to determind if to use, get, post, delete or put</param> /// <param name="body">The body</param> internal static Task<string> PerformAsync(Dinero dinero, Uri baseUri, Dictionary<string, string> requestParameters, HttpType httpType, string body = "") { var url = BuildUri(dinero, baseUri, requestParameters).AbsoluteUri; var httpContent = new StringContent(body, Encoding.UTF8, "application/json"); return WorkAsync(dinero, httpType, url, httpContent); }
private static async Task<HttpResponseMessage> GetResponse(Dinero dinero, HttpType method, string url, HttpContent httpContent, HttpClient httpClient, string contentType = "application/json") { var token = dinero.GetAuthorizationToken(); httpClient.SetBearerToken(token.AccessToken); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); HttpResponseMessage response; switch (method) { case HttpType.GET: response = await httpClient.GetAsync(new Uri(url)); break; case HttpType.DELETE: response = await httpClient.DeleteAsync(new Uri(url)); break; case HttpType.POST: response = await httpClient.PostAsync(new Uri(url), httpContent); break; case HttpType.PUT: response = await httpClient.PutAsync(new Uri(url), httpContent); break; default: throw new ArgumentException("Unknown HttpType: " + method); } if (response.IsSuccessStatusCode) return response; var content = TaskHelper.ExecuteSync(response.Content.ReadAsStringAsync); switch (response.StatusCode) { case (System.Net.HttpStatusCode)429: throw new DineroThrottleException(content); default: { ResponseBody responseBody; if (TryParseResponseBody(content, out responseBody)) { throw new DineroApiException(responseBody, response.StatusCode); } else { if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) throw new DineroAuthenticationException(content); throw new DineroException( string.Format("The call to the Dinero API did not resolve successfully: ({0}) {1}", response.StatusCode, content)); } } } }
/// <summary> /// Download data from the API. /// </summary> /// <param name="dinero">An instance of the Dinero class. This is needed since it know about the user, the app and their credentials.</param> /// <param name="method">Method to be used for the request. Currently just GET.</param> /// <param name="url">URL to download the data from.</param> /// <param name="httpContent"></param> /// <exception cref="DineroAuthenticationException">This exception is thrown if the authorization fails</exception> private static async Task<string> WorkAsync(Dinero dinero, HttpType method, string url, HttpContent httpContent) { using (var httpClient = new HttpClient()) { var response = await GetResponse(dinero, method, url, httpContent, httpClient); return await response.Content.ReadAsStringAsync(); } }
/// <summary> /// Download data from the API. /// </summary> /// <param name="dinero">An instance of the Dinero class. This is needed since it know about the user, the app and their credentials.</param> /// <param name="method">Method to be used for the request. Currently just GET.</param> /// <param name="url">URL to download the data from.</param> /// <param name="httpContent"></param> /// <exception cref="DineroAuthenticationException">This exception is thrown if the authorization fails</exception> private static async Task<Stream> WorkAsyncStream(Dinero dinero, HttpType method, string url, HttpContent httpContent) { using (var httpClient = new HttpClient()) { var response = await GetResponse(dinero, method, url, httpContent, httpClient, "application/octet-stream"); return await response.Content.ReadAsStreamAsync(); } }
/// <summary> /// 访问接口并返回OperateResult类型对象及数据 /// </summary> /// <typeparam name="T1">OperateResult类型对象</typeparam> /// <typeparam name="T2">数据</typeparam> /// <param name="url">接口地址</param> /// <param name="type">访问类型,HttpType</param> /// <param name="param">参数,对象形式自动转换,或json字符串</param> /// <param name="replaceList">替换数组</param> /// <param name="standardResult">是否返回标准的OperateResult,默认是,false则会自动组装</param> /// <param name="timeOut">超时时间</param> /// <returns>返回OperateResult类型对象及数据</returns> public T1 HttpRequest <T1, T2>(string url, HttpType type = HttpType.Get, object param = null, IDictionary <int, List <string> > replaceList = null, bool standardResult = true, int timeOut = 300000) where T1 : OperateResult <T2>, new() { HttpWebRequest request = null; HttpWebResponse response = null; StreamReader reader = null; Stream outStream = null; try { //构造http请求的对象 request = (HttpWebRequest)WebRequest.Create(url); //设置 request.ProtocolVersion = HttpVersion.Version11; request.Method = type.ToString().Replace("Form", "Post"); request.KeepAlive = false; request.Timeout = timeOut; var data = ""; if (param != null) { var name = param.GetType().Name; if (!("String,Int32,Int64").Contains(name)) { if (type.Equals(HttpType.Form)) { data = ObjectUtil.ToFormUrlEncoded(param); } else { data = JsonUtil.ToJson(param); } } else { data = param.ToString(); } } if (!string.IsNullOrEmpty(this.Token)) { request.Headers["Authorization"] = string.Format("Bearer {0}", this.Token); } if (Headers != null && Headers.Count > 0) { foreach (var h in this.Headers) { if (h.Value != null) { request.Headers[h.Key] = h.Value.ToString(); } } } if (data.Trim() != "") { if (type.Equals(HttpType.Form)) { request.ContentType = @"application/x-www-form-urlencoded"; } else { request.ContentType = @"application/json"; } request.MediaType = "application/json"; request.Accept = "application/json"; request.Headers["Accept-Language"] = "zh-CN,zh;q=0."; request.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3"; //转成网络流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); request.ContentLength = buf.Length; outStream = request.GetRequestStream(); outStream.Flush(); outStream.Write(buf, 0, buf.Length); outStream.Flush(); outStream.Close(); } else if (type.Equals(HttpType.Post) || type.Equals(HttpType.Form) || type.Equals(HttpType.Put)) { request.ContentLength = 0; } // 获得接口返回值 response = (HttpWebResponse)request.GetResponse(); reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); reader.Close(); response.Close(); request.Abort(); if (replaceList != null && replaceList.Count == 2) { for (var i = 0; i < replaceList[0].Count; i++) { content = content.Replace(replaceList[0][i], replaceList[1][i]); } } if (!standardResult) { content = string.Format("{{\"Data\":{0}, \"OperateStatus\":1}}", content); } var result = JsonUtil.FromJson <T1>(content); return(result); } catch (Exception ex) { if (outStream != null) { outStream.Close(); } if (reader != null) { reader.Close(); } if (response != null) { response.Close(); } if (request != null) { request.Abort(); } string error = ex.Message; var result = new T1() { OperateStatus = Common.Enums.OperateStatus.Failed, Message = error }; return(result); } }
public HalRepresentation AddLink(string rel, string href, HttpType type) { this._links.Add(new KeyValuePair <string, HalLink>(rel, new HalLink(href, type))); return(this); }
public HalLink(string href, HttpType type) { Href = href; Type = Enum.GetName(typeof(HttpType), type); }
public HttpRequest(string url, string body, HttpType httpType) { URL = url; Body = body; HttpType = httpType; }
public static bool RequestWithXmldata(out HttpWebResponse response, string url, HttpType method, string data) { response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToString(); response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { response = (HttpWebResponse)e.Response; } else { return(false); } } catch (Exception) { if (response != null) { response.Close(); } return(false); } return(true); }
public ThirdPayModel(string url, HttpType type, object data) : this(url) { Type = type; Data = data; }
public ThirdPayModel(HttpType type, object data) { Type = type; Data = data; }
/// <summary> /// Http通用请求 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="uri"></param> /// <param name="type"></param> /// <param name="inputData"></param> /// <returns></returns> public static string HttpRequest(string ip, string port, string uri, HttpType type, string inputData = "") { string url = "http://" + ip + ":" + port + uri; return(HttpRequest(url, type, inputData)); }
protected virtual void CustomValidate(MISAEntity entity, HttpType http) { }