private static string GetExceptionMessage(HttpResponseMessage responseMessage) { if (responseMessage == null) { throw new ArgumentNullException("responseMessage"); } return responseMessage.ToString(); }
public async Task <JObject> GetJsonAsync() { Debug.WriteLine(uri); using (var client = new System.Net.Http.HttpClient()) { string jsonString = ""; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (type == RequestType.GET) { jsonString = await client.GetStringAsync(uri); Debug.WriteLine(jsonString); } else if (type == RequestType.POST) { CreateJsonContent(); System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, new StringContent(obj.ToString(), Encoding.UTF8, "application/json")); Debug.WriteLine("response : " + response.ToString()); jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); } else if (type == RequestType.DELETE) { System.Net.Http.HttpResponseMessage response = await client.DeleteAsync(uri); Debug.WriteLine("response : " + response.StatusCode.ToString()); jsonString = await response.Content.ReadAsStringAsync(); } Debug.WriteLine("jsonstring : " + jsonString); return(JObject.Parse(jsonString)); } }
public static async Task PrintResponse (HttpResponseMessage response) { Debug ("RESPONSE:"); Debug (response.ToString ()); if (response.Content != null) { var respBody = await response.Content.ReadAsStringAsync (); Debug (respBody.Substring (0, Math.Min (MaxBodyLength, respBody.Length)) + (respBody.Length >= MaxBodyLength ? "(...)" : "")); } }
public async Task SetResponseAsync(HttpResponseMessage httpResponseMessage) { _stopwatch.Stop(); _responseLog.Headers = httpResponseMessage.ToString(); _responseLog.StatusCode = httpResponseMessage.StatusCode; if (httpResponseMessage.Content != null) { _responseLog.Body = await httpResponseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false); } }
protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) { if (response != null) { this.logger.LogMessage(response.ToString(), Severity.Informational, Verbosity.Detailed); if (response.Content != null) { this.logger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Payload: {0} ", response.Content.ReadAsStringAsync().Result), Severity.Informational, Verbosity.Detailed); } } return response; }
public void Ctor_Default () { var m = new HttpResponseMessage (); Assert.IsNull (m.Content, "#1"); Assert.IsNotNull (m.Headers, "#2"); Assert.IsTrue (m.IsSuccessStatusCode, "#3"); Assert.AreEqual ("OK", m.ReasonPhrase, "#4"); Assert.IsNull (m.RequestMessage, "#5"); Assert.AreEqual (HttpStatusCode.OK, m.StatusCode, "#6"); Assert.AreEqual (new Version (1, 1), m.Version, "#7"); Assert.IsNull (m.Headers.CacheControl, "#8"); Assert.AreEqual ("StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: <null>, Headers:\r\n{\r\n}", m.ToString (), "#9"); }
public static void LogResponseOnFailedAssert(this ILogger logger, HttpResponseMessage response, string responseText, Action assert) { try { assert(); } catch (XunitException) { logger.LogWarning(response.ToString()); if (!string.IsNullOrEmpty(responseText)) { logger.LogWarning(responseText); } throw; } }
// GET api/values/5 public string Get(string id) { if (id == "3") { Quix.Auth auth = new Quix.Auth( System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString(), System.Configuration.ConfigurationManager.AppSettings["TenantId"].ToString(), System.Configuration.ConfigurationManager.AppSettings["TenantUrl"].ToString(), System.Configuration.ConfigurationManager.AppSettings["AccessScopes"].ToString().Split(','), System.Configuration.ConfigurationManager.AppSettings["TokenFile"].ToString()); System.Net.Http.HttpClient client = auth.GetHttpClient(); System.Net.Http.HttpResponseMessage response = client.GetAsync("https://cjvandyk.sharepoint.com/sites/Approval/_api/web/lists/GetByTitle('Approval')/items?$select=Title,ID&$filter=Title%20eq%20%27Test%27").GetAwaiter().GetResult(); return("value {" + id + "}" + response.ToString()); } return("value {" + (Convert.ToInt16(id) + 27) + "}"); }
public void ReceiveResponse(string invocationId, HttpResponseMessage response) { Write("{0}: ReceiveResponse {1}", invocationId, response.ToString()); }
public void Headers_ConnectionClose () { HttpResponseMessage message = new HttpResponseMessage (); HttpResponseHeaders headers = message.Headers; Assert.IsNull (headers.ConnectionClose, "#1"); headers.ConnectionClose = false; Assert.IsFalse (headers.ConnectionClose.Value, "#2"); headers.Clear (); headers.ConnectionClose = true; Assert.IsTrue (headers.ConnectionClose.Value, "#3"); headers.Clear (); headers.Connection.Add ("Close"); Assert.IsTrue (headers.ConnectionClose.Value, "#4"); Assert.AreEqual ("StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: <null>, Headers:\r\n{\r\nConnection: Close\r\n}", message.ToString (), "#5"); }
public void Headers_ConnectionClose() { HttpResponseMessage message = new HttpResponseMessage (); HttpResponseHeaders headers = message.Headers; Assert.IsNull (headers.ConnectionClose, "#1"); headers.ConnectionClose = false; Assert.IsFalse (headers.ConnectionClose.Value, "#2"); headers.Clear (); headers.ConnectionClose = true; Assert.IsTrue (headers.ConnectionClose.Value, "#3"); headers.Clear (); headers.Connection.Add ("Close"); Assert.IsTrue (headers.ConnectionClose.Value, "#4"); // .NET encloses the "Connection: Close" with two whitespaces. var normalized = Regex.Replace (message.ToString (), @"\s", ""); Assert.AreEqual ("StatusCode:200,ReasonPhrase:'OK',Version:1.1,Content:<null>,Headers:{Connection:Close}", normalized, "#5"); }
private static void Format(StringBuilder message, HttpResponseMessage response, string header) { HandleErrorHelper.AppendHeader(message, header); message.AppendLine(response == null ? HandleErrorHelper.NULL : response.ToString()); message.AppendLine(); }
internal static void ClientSendCompleted(HttpClient httpClient, HttpResponseMessage response, HttpRequestMessage request) { if (!s_log.IsEnabled()) { return; } string responseString = ""; if (response != null) { responseString = response.ToString(); } s_log.ClientSendCompleted(LoggingHash.HashInt(request), LoggingHash.HashInt(response), responseString, LoggingHash.HashInt(httpClient)); }
protected PayPalPaymentData ExecutePayment(PayPalOAuthTokenData token, string payPalPaymentId, string payer_id, bool useSandbox) { if (string.IsNullOrEmpty(token.access_token)) { throw new ArgumentNullException("token.access_token"); } if (string.IsNullOrEmpty(payPalPaymentId)) { throw new ArgumentNullException("payPalPaymentId"); } if (string.IsNullOrEmpty(payer_id)) { throw new ArgumentNullException("payer_id"); } PayPalPaymentExecuteData executeData = new PayPalPaymentExecuteData(payer_id); string executeJson = JsonConvert.SerializeObject(executeData); StringContent postContent = new StringContent(executeJson, Encoding.UTF8, "application/json"); HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(0, 0, 30); Uri requestUri = null; if (useSandbox) { httpClient.BaseAddress = new Uri("https://api.sandbox.paypal.com/"); } else { httpClient.BaseAddress = new Uri("https://api.paypal.com/"); } requestUri = new Uri("v1/payments/payment/" + payPalPaymentId + "/execute", UriKind.Relative); HttpResponseMessage response = new HttpResponseMessage(); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token); try { response = httpClient.PostAsync(requestUri, postContent).Result; } catch (Exception ex) { string message = "HTTP Client returned an error during PayPal Execute Payment API post: " + ex.Message + ". See inner exception for details."; throw new Exceptions.PayPalExceptionExecutePaymentFailed(useSandbox, message, null, ex); } PayPalPaymentData executePaymentResponse; if (response.IsSuccessStatusCode) { //get PayPal data string json = response.Content.ReadAsStringAsync().Result; try { executePaymentResponse = JsonConvert.DeserializeObject<PayPalPaymentData>(json); } catch (Exception ex) { string message = "Error reading PayPal Execute Payment API result! \nError code: " + response.StatusCode + " " + response.ReasonPhrase + "\n" + response.ToString() + " see inner exception for details.\nJSON Response Data: " + json; throw new Exceptions.PayPalExceptionExecutePaymentFailed(useSandbox, message, response, ex); } executePaymentResponse.Json = json; } else { string message = "PayPal Execute Payment API call failed! \nError code: " + response.StatusCode + " " + response.ReasonPhrase + "\n" + response.ToString(); throw new Exceptions.PayPalExceptionExecutePaymentFailed(useSandbox, message, response, null); } return executePaymentResponse; }
public async Task<Exception> GetExceptionFromResponse(HttpResponseMessage response) { var result = await response.Content.ReadAsStringAsync(); var error = JsonConvert.DeserializeObject<Error>(result); if (error.Type == null) { var msg = FormatMessage((int)response.StatusCode, response.ReasonPhrase + "."); var exp = new ServiceCallExcepton(msg, response, new Exception(response.ToString())) { HelpLink = GetHelpLink((int)response.StatusCode) }; return exp; } var type = Type.GetType(error.Type); Exception exception; if (type == null) { return new ExpectedIssues(_configuration).GetException(ExpectedIssues.ServiceCallError, new Exception(response.ToString())); } else { try { exception = (Exception)Activator.CreateInstance(type, "The service throw an exception. " + error.Message); } catch (Exception exp) { exception = new InvalidOperationException(error.Message, exp); } } if (error.Data != null) { foreach (var data in error.Data) { exception.Data.Add(data.Key, data.Value); } } return exception; }