private dynamic JsonPostRequest(ApiMethod methodName, JObject jsonPostData) { string error; var methodNameStr = Char.ToLowerInvariant(methodName.ToString()[0]) + methodName.ToString().Substring(1); dynamic data = HttpHelper.Post( new Uri(Scheme + "://" + Host + "/" + methodNameStr), JsonConvert.SerializeObject(jsonPostData, Formatting.Indented), out error ); if (String.IsNullOrEmpty(error)) { if (data == null) { error = "Got empty or invalid response from API"; } else { return(data); } } else { error = "HTTP or JSON error: " + error; } DebugHelper.Out(error, DebugHelper.Type.Error); return(false); }
private T PostRequest <T>(ApiMethod method, string jsonData) where T : class { var methodName = char.ToLowerInvariant(method.ToString()[0]) + method.ToString().Substring(1); var response = HttpHelper.Post <T>( new Uri(AnticaptchaInfoBase.Scheme + "://" + AnticaptchaInfoBase.Host + "/" + methodName), jsonData); return(response); }
/// <summary> /// Calls API Methods. /// </summary> /// <typeparam name="T">Type to which the response content will be converted.</typeparam> /// <param name="method">HTTPMethod (POST-GET-PUT-DELETE)</param> /// <param name="endpoint">Url endpoing.</param> /// <param name="isSigned">Specifies if the request needs a signature.</param> /// <param name="parameters">Request parameters.</param> /// <returns></returns> public async Task <T> CallAsync <T>(ApiMethod method, string endpoint, bool isSigned = false, string parameters = null) { var finalEndpoint = endpoint + (string.IsNullOrWhiteSpace(parameters) ? "" : $"?{parameters}"); if (isSigned) { // Joining provided parameters parameters += (!string.IsNullOrWhiteSpace(parameters) ? "×tamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now.ToUniversalTime()); // Creating request signature var signature = Utilities.GenerateSignature(_apiSecret, parameters); finalEndpoint = $"{endpoint}?{parameters}&signature={signature}"; } var request = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint); var response = await _httpClient.SendAsync(request).ConfigureAwait(false); if (response.IsSuccessStatusCode) { // Api return is OK response.EnsureSuccessStatusCode(); // Get the result var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // Serialize and return result return(JsonConvert.DeserializeObject <T>(result)); } // We received an error if (response.StatusCode == HttpStatusCode.GatewayTimeout) { //throw new Exception("Api Request Timeout."); Console.WriteLine("\n***BinanceClient::CallAsync<T>=> Api Request Timeout\n"); return(default(T)); } // Get te error code and message var e = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // Error Values var eCode = 0; string eMsg = ""; if (e.IsValidJson()) { try { var i = JObject.Parse(e); eCode = i["code"]?.Value <int>() ?? 0; eMsg = i["msg"]?.Value <string>(); } catch { } } //throw new Exception(string.Format("Api Error Code: {0} Message: {1}", eCode, eMsg)); ErrorMessage(string.Format("***BinanceClient::CallAsync<T>=> Api Error Code: {0} Message: {1}", eCode, eMsg)); return(default(T)); // Task.FromResult(default(T)); }
/// <see cref="IApiClient.CallAsync{T}(ApiMethod, string, bool, string)"/> public async Task <T> CallAsync <T>(ApiMethod method, string endpoint, string parameters = null, object data = null) { try { var finalEndpoint = endpoint + (string.IsNullOrWhiteSpace(parameters) ? "" : $"?{parameters}"); if (method != ApiMethod.GET) { _httpClient.DefaultRequestHeaders.Remove("nonce"); _httpClient.DefaultRequestHeaders.Add("nonce", DateTime.Now.GetUnixTimeStamp()); } var request = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint); if (data != null) { request.Content = new StringContent(JsonConvert.SerializeObject(data)); } var response = await _httpClient.SendAsync(request).ConfigureAwait(false); // Get the result var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // Serialize and return result return(JsonConvert.DeserializeObject <T>(result)); } catch (Exception ex) { logger.Error(ex, "An error has occurred!"); throw ex; } }
private Result <T> Request <T>( ApiMethod method, string uri, ApiQueryField[] apiQueryFields, JToken jsonRequest, HttpStatusCode expectedStatusCode, bool readJsonResponse, Func <string, T> parseResponse) { Result <T> result; string xrfKey = GenerateXrfKey(); var apiQueryFieldList = new List <ApiQueryField> { new ApiQueryField("Xrfkey", xrfKey) }; if (apiQueryFields != null) { apiQueryFieldList.AddRange(apiQueryFields); } string fullUri = ComposeUri(uri, apiQueryFieldList); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri); request.Method = method.ToString().ToUpperInvariant(); request.Headers.Add("X-Qlik-Xrfkey", xrfKey); request.Headers.Add("X-Qlik-User", $"UserDirectory={_user.UserDirectory}; UserId={_user.UserId}"); request.Accept = "application/json"; request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = (int)TimeSpan.FromSeconds(ApiTimeoutSeconds).TotalMilliseconds; if (_clientCertificate != null) { request.ClientCertificates.Add(_clientCertificate); } WriteJsonRequest(jsonRequest, request); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == expectedStatusCode) { string jsonResponse = ReadJsonResponse(readJsonResponse, response); result = new Result <T>(true, parseResponse(jsonResponse)); } else { result = new Result <T>(false, default(T)); } } return(result); }
/// <summary> /// Calls API Methods. /// </summary> /// <typeparam name="T">Type to which the response content will be converted.</typeparam> /// <param name="method">HTTPMethod (POST-GET-PUT-DELETE)</param> /// <param name="endpoint">Url endpoing.</param> /// <param name="isSigned">Specifies if the request needs a signature.</param> /// <param name="parameters">Request parameters.</param> /// <returns></returns> public async Task <T> CallAsync <T>(ApiMethod method, string endpoint, bool isSigned = false, string parameters = null) { var finalEndpoint = endpoint + (string.IsNullOrWhiteSpace(parameters) ? "" : $"?{parameters}"); if (isSigned) { parameters += (!string.IsNullOrWhiteSpace(parameters) ? "×tamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now); var signature = Utilities.GenerateSignature(_apiSecret, parameters); finalEndpoint = $"{endpoint}?{parameters}&signature={signature}"; } var request = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint); var response = await _httpClient.SendAsync(request).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return(JsonConvert.DeserializeObject <T>(result)); }
/// <summary> /// Calls API Methods. /// </summary> /// <typeparam name="T">Type to which the response content will be converted.</typeparam> /// <param name="method">HTTPMethod (POST-GET-PUT-DELETE)</param> /// <param name="endpoint">Url endpoing.</param> /// <param name="isSigned">Specifies if the request needs a signature.</param> /// <param name="parameters">Request parameters.</param> /// <returns></returns> public async Task <T> CallAsync <T>(ApiMethod method, string endpoint, bool isSigned = false, string parameters = null) { var finalEndpoint = endpoint + (string.IsNullOrWhiteSpace(parameters) ? "" : $"?{parameters}"); if (isSigned) { parameters += (!string.IsNullOrWhiteSpace(parameters) ? "×tamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now); var signature = Utilities.GenerateSignature(_apiSecret, parameters); finalEndpoint = $"{endpoint}?{parameters}&signature={signature}"; } var request = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint); //Thread.Sleep(500); Console.WriteLine(finalEndpoint); var response = await _httpClient.SendAsync(request).ConfigureAwait(true); //Console.WriteLine(response.Headers); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(true); if (result.StartsWith("{\"code\":-")) { throw new Exception(result); } else { try { T resultObj = JsonConvert.DeserializeObject <T>(result); return(resultObj); } catch (Exception ex) { throw new Exception(string.Format("解析异常: 返回消息 {0} 转为 {1}时失败,异常信息{2}", result, typeof(T).Name, ex.Message)); } } }
public static async void Request <T>(Action <T> callback, string endpoint, ApiMethod method = ApiMethod.GET, Dictionary <string, object> data = null, Action <HttpWebRequest> setup = null) { try { var uri = new UriBuilder(API_URL + endpoint); var query = new StringBuilder(uri.Query); if (query.Length > 0) { query.Remove(0, 1); } if (method == ApiMethod.GET && data != null) { foreach (var pair in data) { if (query.Length > 0) { query.Append('&'); } query.Append(pair.Key); query.Append('='); if (pair.Value != null) { query.Append(Uri.EscapeDataString(pair.Value.ToString())); } } } if (!string.IsNullOrEmpty(m_ApiKey) && !"config".Equals(uri.Path)) { query.Insert(0, "apiKey=" + m_ApiKey + (query.Length > 0 ? "&" : string.Empty)); } uri.Query = query.ToString(); var request = WebRequest.CreateHttp(uri.Uri); request.CookieContainer = m_CookieContainer; request.KeepAlive = true; request.Method = method.ToString(); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"; if (setup != null) { setup.Invoke(request); } if (method != ApiMethod.GET && data != null) { request.ContentType = "application/json;charset=utf-8"; using (var stream = await request.GetRequestStreamAsync()) { using (var writer = new StreamWriter(stream)) { JSON.SerializeDynamic(data, writer); } } } using (var response = await request.GetResponseAsync() as HttpWebResponse) { HandleJson(response, callback); } } catch (WebException w) { try { using (var response = w.Response as HttpWebResponse) { if (response.ContentType != null && response.ContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) != -1) { HandleJson <ApiResponse>(response, MainForm.Instance.OnResponse); } else { MainForm.Instance.ShowMessage(endpoint + ": " + w.Message); } } } catch (Exception x) { MainForm.Instance.ShowMessage(endpoint + ": " + x.Message); } } catch (Exception x) { MainForm.Instance.ShowMessage(endpoint + ": " + x.Message); } }
/// <summary> /// To make a call to the APROPLAN api /// </summary> /// <param name="uri">The url to call</param> /// <param name="method">The method to use to make the call</param> /// <param name="queryParams">The query params collection to use</param> /// <param name="data">The data to send through the request</param> /// <param name="stream">If you upload something, this is the stream containing the data to upload</param> /// <returns>The response of the request as a string</returns> private async Task <HttpResponse> Request(string uri, ApiMethod method, IDictionary <string, string> queryParams, string data, Stream stream, string contentType) { WriteLogRequest(uri, method, queryParams, data, stream); int nb = 0; if (uri != _resourceRenew) { if ((RequestLoginState == RequestLoginState.NotConnected || !IsTokenValid()) && !_resourcesWithoutConnection.Contains(new Tuple <ApiMethod, String>(method, uri))) { throw new ApiException("Cannot call API without to be connected", "NOT_CONNECTED", null, uri, -1, method.ToString(), null); } } if (!_resourcesLogin.Contains(uri) && uri != _resourceRenew) { while ((RequestLoginState == RequestLoginState.Connecting || RequestLoginState == RequestLoginState.Renewing) && nb < 10) { Thread.Sleep(300); nb++; } } UriBuilder uriBuilder = new UriBuilder(uri); Dictionary <string, string> allQueryParams = BuildDefaultQueryParams(); if (queryParams != null && queryParams.Count > 0) { foreach (var keyPair in queryParams) { allQueryParams.Add(keyPair.Key, keyPair.Value); } } uriBuilder.Query = new FormUrlEncodedContent(allQueryParams).ReadAsStringAsync().Result; // Post To GET when url is too long if (uriBuilder.Uri.ToString().Length >= 1500 && method.ToString().ToUpperInvariant() == "GET") { var newUriBuilder = new UriBuilder(ApiRootUrl + "posttoget"); newUriBuilder.Query = new FormUrlEncodedContent(BuildDefaultQueryParams()).ReadAsStringAsync().Result; var action = uriBuilder.Path.Split('/').Last(); string paramsPostToGet = ""; foreach (var param in queryParams) { paramsPostToGet += (paramsPostToGet.Length > 0 ? "&" : "") + $"{param.Key}={param.Value}"; } var dataPost = new { EntityAction = action, Params = paramsPostToGet }; data = JsonConvert.SerializeObject(dataPost, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); method = ApiMethod.Post; uriBuilder = newUriBuilder; } WebRequest request = WebRequest.Create(uriBuilder.Uri); request.Method = method.ToString().ToUpperInvariant(); //stream = request.GetRequestStream(); if (!String.IsNullOrEmpty(data)) { byte[] byteArray = Encoding.UTF8.GetBytes(data); request.ContentType = "application/json"; request.ContentLength = byteArray.Length; using (stream = request.GetRequestStream()) { stream.Write(byteArray, 0, byteArray.Length); } } else if (stream != null) { var oldPosition = stream.Position; stream.Position = 0; request.ContentType = contentType; request.ContentLength = stream.Length; stream.CopyTo(request.GetRequestStream()); stream.Position = oldPosition; } try { using (WebResponse response = await request.GetResponseAsync()) { using (stream = response.GetResponseStream()) { StreamReader streamReader = new StreamReader(stream); string dataString = streamReader.ReadToEnd(); if (_logger != null) { string debugMsg = $"API response of {method} to {uri}\r\n\r\n"; debugMsg += "\r\n data: " + (dataString == null ? "<null>" : dataString); _logger.LogDebug(debugMsg); } return(new HttpResponse { Data = dataString, Headers = response.Headers }); } } } catch (WebException ex) { if (ex.Response != null) { string url = ex.Response.ResponseUri.ToString(); string resMethod = method.ToString(); string errorCode = null; string errorId = null; int statusCode = 0; string message = "An error occured while the api call"; HttpWebResponse httpResponse = ex.Response as HttpWebResponse; if (httpResponse != null) { resMethod = httpResponse.Method; statusCode = (int)httpResponse.StatusCode; } using (var streamRes = new StreamReader(ex.Response.GetResponseStream())) { string res = streamRes.ReadToEnd(); if (ex.Response.ContentType.Contains("application/json")) { JArray json = JsonConvert.DeserializeObject <JArray>(res, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Local }); JToken item = json.First; IEnumerable <JProperty> properties = item.Children <JProperty>(); var element = properties.FirstOrDefault(x => x.Name == "Message"); if (element != null) { message = element.Value.ToString(); } element = properties.FirstOrDefault(x => x.Name == "ErrorCode"); if (element != null) { errorCode = element.Value.ToString(); } element = properties.FirstOrDefault(x => x.Name == "ErrorGuid"); if (element != null) { errorId = element.Value.ToString(); } } } throw new ApiException(message, errorCode, errorId, url, statusCode, resMethod, ex); } throw; } catch (Exception ex) { if (ex is ApiException) { throw; } string url = uri; string resMethod = method.ToString(); throw new ApiException("An error occured", null, null, url, 0, resMethod, ex); } }
/// <summary> /// Calls API Methods. /// </summary> /// <typeparam name="T">Type to which the response content will be converted.</typeparam> /// <param name="method">HTTPMethod (POST-GET-PUT-DELETE)</param> /// <param name="endpoint">Url endpoint.</param> /// <param name="isSigned">Specifies if the request needs a signature.</param> /// <param name="parameters">Request parameters.</param> /// <returns></returns> public async Task <T> CallAsync <T>(ApiMethod method, string endpoint, bool isSigned = false, string parameters = null) { string finalEndpoint = endpoint + (string.IsNullOrWhiteSpace(parameters) ? "" : $"?{parameters}"); if (isSigned) { // Joining provided parameters parameters += (!string.IsNullOrWhiteSpace(parameters) ? "×tamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now.ToUniversalTime()); // Creating request signature string signature = Utilities.GenerateSignature(_apiSecret, parameters); finalEndpoint = $"{endpoint}?{parameters}&signature={signature}"; } HttpRequestMessage request = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint); HttpResponseMessage response = await _httpClient.SendAsync(request).ConfigureAwait(false); if (response.IsSuccessStatusCode) { // Api return is OK response.EnsureSuccessStatusCode(); // Get the result string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // Serialize and return result return(JsonConvert.DeserializeObject <T>(result)); } // We received an error if (response.StatusCode == HttpStatusCode.GatewayTimeout) { throw new Exception("Api Request Timeout."); } // Get te error code and message string e = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // Error Values int eCode = 0; string eMsg = ""; if (!e.IsValidJson()) { throw new Exception($"Api Error Code: {eCode} Message: {eMsg}"); } try { JObject i = JObject.Parse(e); eCode = i["code"]?.Value <int>() ?? 0; eMsg = i["msg"]?.Value <string>(); } catch { // ignored } throw new Exception($"Api Error Code: {eCode} Message: {eMsg}"); }
public async Task<JToken> CallApiMethod(ApiMethod method, IEnumerable<KeyValuePair<string, string>> parameters) { return await CallApiMethod(method.ToString().Replace('_', '.'), parameters); }