protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var call = new HttpCall { Request = request }; var stringContent = request.Content as CapturedStringContent; if (stringContent != null) call.RequestBody = stringContent.Content; await RaiseGlobalEventAsync(FlurlHttp.Configuration.BeforeCall, FlurlHttp.Configuration.BeforeCallAsync, call); call.StartedUtc = DateTime.UtcNow; try { call.Response = await base.SendAsync(request, cancellationToken); call.EndedUtc = DateTime.UtcNow; } catch (Exception ex) { call.Exception = ex; } if (call.Exception != null) await RaiseGlobalEventAsync(FlurlHttp.Configuration.OnError, FlurlHttp.Configuration.OnErrorAsync, call); await RaiseGlobalEventAsync(FlurlHttp.Configuration.AfterCall, FlurlHttp.Configuration.AfterCallAsync, call); if (IsErrorCondition(call)) { throw IsTimeout(call, cancellationToken) ? new FlurlHttpTimeoutException(call, call.Exception) : new FlurlHttpException(call, call.Exception); } return call.Response; }
private Task RaiseGlobalEventAsync(Action<HttpCall> syncVersion, Func<HttpCall, Task> asyncVersion, HttpCall call) { if (syncVersion != null) syncVersion(call); if (asyncVersion != null) return asyncVersion(call); return NoOpTask.Instance; }
private void SetUserAgentHeader(HttpCall call) { foreach (ProductInfoHeaderValue userAgent in UserAgents) { call.Request.Headers.UserAgent.Add(userAgent); } }
private static void SetUserAgentHeader(HttpCall call) { foreach (var userAgent in Configuration.UserAgents) { call.Request.Headers.UserAgent.Add(userAgent); } }
public void JsonPostTest() { #region arrange DateTime dateTime = new DateTime(2020, 8, 31, 13, 23, 10); long timestamp = 1598873142327; DateTime dateTime_ts = DateTimeOffset.FromUnixTimeMilliseconds(timestamp).DateTime.ToLocalTime(); string alpha = "12,34"; string beta = "56,78"; string body = "[{\"datetime\":\"" + dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + "\"," + "\"datetime_ts\":\"" + dateTime_ts.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + "\"," + "\"alpha\":" + alpha.Replace(",", ".") + "," + "\"beta\":" + beta.Replace(",", ".") + "}]"; string endPoint = @"https://postman-echo.com/post"; object id = "1234"; CallMethod callMethod = CallMethod.POST; CallContentType callContentType = CallContentType.json; #endregion #region act ICall call = new HttpCall(); IResponseParser parser = new SimpleParser(); Dictionary <string, object> actual = call.doCall(id, callMethod, callContentType, endPoint, parser, body); #endregion #region assert Assert.IsNotNull(actual); Assert.IsTrue(actual.Count == 1); Assert.IsTrue(actual.ContainsKey("Response")); #endregion }
private async Task <HttpCall> Send(RestRequest request, bool retryInvalidToken) { string url = _instanceUrl + request.Path; var headers = request.AdditionalHeaders != null ? new HttpCallHeaders(_accessToken, request.AdditionalHeaders) : new HttpCallHeaders(_accessToken, new Dictionary <string, string>()); HttpCall call = await new HttpCall(request.Method, headers, url, request.RequestBody, request.ContentType).Execute() .ConfigureAwait(false); if (!call.HasResponse) { throw call.Error; } if (call.StatusCode == HttpStatusCode.Unauthorized || call.StatusCode == HttpStatusCode.Forbidden) { if (retryInvalidToken && _accessTokenProvider != null) { string newAccessToken = await _accessTokenProvider(); if (newAccessToken != null) { _accessToken = newAccessToken; call = await Send(request, false); } } } // Done return(call); }
private static void LogReq(HttpCall obj) { if (Pazpar2Settings.LOG_HTTP_REQUESTS) { Pici.Log.debug(typeof(UrlHelper), String.Format("\r\n\tREQUEST: {0}\r\n\t{1} {2}", obj.GetHashCode(), obj.Request.Method, obj.Url)); } }
private async Task HandleFlurlErrorAsync(HttpCall call) { if (call.Exception.GetType() != typeof(Flurl.Http.FlurlParsingException)) { await LogErrorAsync(call.Exception.Message); } call.ExceptionHandled = true; }
public static void Process404(HttpCall call) { //call.Response.Headers[HttpResponseHeader.ContentType] = "text/plain"; call.Response.StatusCode = 404; //call.Response.StatusDescription = "Not found"; //call.Write("Not found"); call.Out.Close(); }
/// <summary> /// Send request asynchronous. /// </summary> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var call = HttpCall.Get(request); var stringContent = request.Content as CapturedStringContent; if (stringContent != null) { call.RequestBody = stringContent.Content; } await FlurlHttp.RaiseEventAsync(request, FlurlEventType.BeforeCall).ConfigureAwait(false); call.StartedUtc = DateTime.UtcNow; try { call.Response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); call.EndedUtc = DateTime.UtcNow; } catch (OperationCanceledException ex) { call.Exception = (cancellationToken.IsCancellationRequested) ? new FlurlHttpException(call, ex) : new FlurlHttpTimeoutException(call, ex); } catch (Exception ex) { call.Exception = new FlurlHttpException(call, ex); } if (call.Response != null && !call.Succeeded) { if (call.Response.Content != null) { call.ErrorResponseBody = await call.Response.Content.StripCharsetQuotes().ReadAsStringAsync().ConfigureAwait(false); } call.Exception = new FlurlHttpException(call, null); } if (call.Exception != null) { await FlurlHttp.RaiseEventAsync(request, FlurlEventType.OnError).ConfigureAwait(false); } await FlurlHttp.RaiseEventAsync(request, FlurlEventType.AfterCall).ConfigureAwait(false); if (call.Exception != null && !call.ExceptionHandled) { throw call.Exception; } if (call.Response != null) { call.Response.RequestMessage = request; } return(call.Response); }
public override void ScenarioSetup() { base.ScenarioSetup(); HttpCall.Setup(_ => _.HttpCall(It.IsAny <Uri>(), It.IsAny <IHttpOptions>(), It.IsAny <CancellationToken>())) .ReturnsAsync(Return.Ok( BaseUrl, new MemoryStream(), WithHeaders("Link", $"<{BaseUrl}api/documentation>; rel=\"next\""))); }
public override void ScenarioSetup() { base.ScenarioSetup(); HttpCall.Setup(_ => _.HttpCall(new Uri(BaseUrl, "api/documentation"), It.IsAny <IHttpOptions>(), It.IsAny <CancellationToken>())) .ReturnsAsync(Return.Ok( new Uri(BaseUrl, "api/documentation"), new MemoryStream(), WithHeaders("Content-Type", "text/turtle"))); }
public async Task <IEnumerable <DropdownDto> > GetHotels() { var hotel = await HttpCall.GetRequest <List <DropdownDto> >("https://localhost:5002/Dropdown/GetHotel"); var rooms = await HttpCall.GetRequest <List <DropdownDto> >("https://localhost:5002/Dropdown/GetRooms"); hotel.AddRange(rooms); return(hotel); }
private Task Given_the_user_is_about_to_call_a_nonexisting_url() { _restCall = new HttpCall( "https://googlewdwwfwef.com/", HttpCallMethodType.Post, new BasicAuthCredentials("Tra", "Tra")); return(Task.CompletedTask); }
private HttpStatusCode DoDescribe(string authToken) { string describeAccountPath = "/services/data/v26.0/sobjects/Account/describe"; Dictionary <string, string> headers = (authToken == null ? null : new Dictionary <string, string> { { "Authorization", "Bearer " + authToken } }); return(HttpCall.CreateGet(headers, TestCredentials.INSTANCE_SERVER + describeAccountPath).Execute().Result.StatusCode); }
private async Task <HttpStatusCode> DoDescribe(string authToken) { string describeAccountPath = "/services/data/v33.0/sobjects/Account/describe"; var headers = new HttpCallHeaders(authToken, new Dictionary <string, string>()); HttpCall result = await HttpCall.CreateGet(headers, TestCredentials.INSTANCE_SERVER + describeAccountPath).Execute(); return(result.StatusCode); }
public async Task <IEnumerable <DropdownDto> > GetRestaurants() { var restaurants = await HttpCall.GetRequest <List <DropdownDto> >("https://localhost:44369/Dropdown/GetRestaurants"); var foods = await HttpCall.GetRequest <List <DropdownDto> >("https://localhost:44369/Dropdown/GetFoods"); restaurants.AddRange(foods); return(restaurants); }
private async Task <HttpStatusCode> DoDescribe(string authToken) { string describeAccountPath = "/services/data/" + ApiVersionStrings.VersionNumber + "/sobjects/Account/describe"; var headers = new HttpCallHeaders(authToken, new Dictionary <string, string>()); HttpCall result = await HttpCall.CreateGet(headers, TestCredentials.InstanceServer + describeAccountPath).ExecuteAsync(); return(result.StatusCode); }
private static string SerializeHttpCall(HttpCall httpCall) { var settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; return(JsonConvert.SerializeObject(httpCall, Formatting.Indented, settings)); }
public void should_obtain_JSON_LD_context() { HttpCall.Verify( _ => _.HttpCall( new Uri(new Uri("http://temp.uri/api", UriKind.Absolute), "context.jsonld"), It.Is <IHttpOptions>(opts => opts.Headers["Accept"] == "application/ld+json"), It.IsAny <CancellationToken>()), Times.Once); }
public async Task <IEnumerable <DropdownDto> > GetFlights() { var flights = await HttpCall.GetRequest <List <DropdownDto> >("https://localhost:44300/DropDown/GetFlights"); var seats = await HttpCall.GetRequest <List <DropdownDto> >("https://localhost:44300/DropDown/GetSeats"); flights.AddRange(seats); return(flights); }
internal static bool HasAnyQueryParam(this HttpCall call, string[] names) { var qp = call.FlurlRequest.Url.QueryParams; return(names.Any() ? qp .Select(p => p.Name) .Intersect(names) .Any() : qp.Any()); }
public void WritePNG(Image image, HttpCall call) { call.Response.ContentType = "image/png"; using (MemoryStream ms = new MemoryStream()) { image.Save(ms, ImageFormat.Png); ms.Position = 0; call.Write(ms); } }
public void WriteIcon(Icon image, HttpCall call) { call.Response.ContentType = "image/vnd.microsoft.icon"; using (MemoryStream ms = new MemoryStream()) { image.Save(ms); ms.Position = 0; call.Write(ms); } }
private async Task <MobileMetadataDownloadResponse> GetRemoteData(CancellationToken cancellationToken = default(CancellationToken)) { var metadata = User.Settings.Routes.Metadata(); using (var response = await HttpCall.GetStreamAsync(metadata, cancellationToken)) { var json = response.ReadToEnd(); var jobject = JsonConvert.DeserializeObject <MobileMetadataDownloadResponseDefinition>(json); return(JsonDownloadMetadataParser.ParseMetadata(jobject)); } }
private async void OnTimedHttpCallEvent(object sender, ElapsedEventArgs e) { //Remove RETURN statement when API endpoint is ready return; if (LatLonCollection.Any()) { await HttpCall.CallNetwork(LatLonCollection[0]); } }
public async Task Run(Worker worker, string uri = "http://test") { var call = new HttpCall() { HttpType = HttpCallTypeEnum.Get, Uri = new Uri(uri) }; await worker.AddCall(call); }
public HttpRequestMessage Adapt(HttpCall restCall) { var httpMethod = MapHttpMethod(restCall.MethodType); var request = new HttpRequestMessage(httpMethod, restCall.RequestUri); CheckAddBody(request, restCall.Body); ApplyBasicAuth(request, restCall.Credentials); return(request); }
private void ErrorHandler(HttpCall call) { if (call.Completed) { string responseContent = call.Response.Content.ReadAsStringAsync().Result; call.ExceptionHandled = true; throw new FlurlHttpException(call, responseContent, call.Exception); } }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var settings = request.GetFlurlSettings(); var call = new HttpCall { Request = request }; var stringContent = request.Content as CapturedStringContent; if (stringContent != null) { call.RequestBody = stringContent.Content; } await RaiseGlobalEventAsync(settings.BeforeCall, settings.BeforeCallAsync, call); call.StartedUtc = DateTime.UtcNow; try { call.Response = await base.SendAsync(request, cancellationToken); call.EndedUtc = DateTime.UtcNow; } catch (Exception ex) { call.Exception = (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested) ? new FlurlHttpTimeoutException(call, ex) : new FlurlHttpException(call, ex); } if (call.Response != null && !call.Succeeded) { if (call.Response.Content != null) { call.ErrorResponseBody = await call.Response.Content.ReadAsStringAsync(); } call.Exception = new FlurlHttpException(call, null); } if (call.Exception != null) { await RaiseGlobalEventAsync(settings.OnError, settings.OnErrorAsync, call); } await RaiseGlobalEventAsync(settings.AfterCall, settings.AfterCallAsync, call); if (call.Exception != null && !call.ExceptionHandled) { throw call.Exception; } call.Response.RequestMessage = request; return(call.Response); }
private Task Given_the_user_is_about_to_fetch_comments_per_post_id() { var url = $"https://jsonplaceholder.typicode.com/comments?postId={PostId}"; _restCall = new HttpCall( url, HttpCallMethodType.Get, new BasicAuthCredentials("Tra", "Tra")); return(Task.CompletedTask); }
/// <summary> /// Async method to call the identity service (to get the mobile policy among other pieces of information) /// </summary> /// <param name="idUrl"></param> /// <param name="accessToken"></param> /// <returns></returns> public static async Task <IdentityResponse> CallIdentityServiceAsync(string idUrl, string accessToken) { LoggingService.Log("Calling identity service", LoggingLevel.Verbose); // Auth header var headers = new HttpCallHeaders(accessToken, new Dictionary <string, string>()); // Get HttpCall c = HttpCall.CreateGet(headers, idUrl); // ExecuteAsync get return(await c.ExecuteAndDeserializeAsync <IdentityResponse>()); }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var settings = request.GetFlurlSettings(); var call = new HttpCall { Request = request }; var stringContent = request.Content as CapturedStringContent; if (stringContent != null) call.RequestBody = stringContent.Content; await RaiseGlobalEventAsync(settings.BeforeCall, settings.BeforeCallAsync, call); call.StartedUtc = DateTime.UtcNow; try { call.Response = await base.SendAsync(request, cancellationToken); call.EndedUtc = DateTime.UtcNow; } catch (Exception ex) { call.Exception = (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested) ? new FlurlHttpTimeoutException(call, ex) : new FlurlHttpException(call, ex); } if (call.Response != null && !call.Succeeded) { if (call.Response.Content != null) call.ErrorResponseBody = await call.Response.Content.ReadAsStringAsync(); call.Exception = new FlurlHttpException(call, null); } if (call.Exception != null) await RaiseGlobalEventAsync(settings.OnError, settings.OnErrorAsync, call); await RaiseGlobalEventAsync(settings.AfterCall, settings.AfterCallAsync, call); if (call.Exception != null && !call.ExceptionHandled) throw call.Exception; call.Response.RequestMessage = request; return call.Response; }
private bool IsErrorCondition(HttpCall call) { return (call.Exception != null && !call.ExceptionHandled) || (call.Response != null && !call.Response.IsSuccessStatusCode); }
private bool IsTimeout(HttpCall call, CancellationToken token) { return call.Exception != null && call.Exception is TaskCanceledException && !token.IsCancellationRequested; }
private async Task RaiseGlobalEventAsync(Action<HttpCall> syncVersion, Func<HttpCall, Task> asyncVersion, HttpCall call) { if (syncVersion != null) syncVersion(call); if (asyncVersion != null) await asyncVersion(call); }
public RestResponse(HttpCall call) { _call = call; }
private HttpCall SendSync(RestRequest request, bool retryInvalidToken) { string url = _instanceUrl + request.Path; Dictionary<string, string> headers = new Dictionary<string, string>() {}; if (_accessToken != null) { headers["Authorization"] = "Bearer " + _accessToken; } if (request.AdditionalHeaders != null) { headers.Concat(request.AdditionalHeaders); } HttpCall call = new HttpCall(request.Method, headers, url, request.Body, request.ContentType).Execute().Result; if (!call.HasResponse) { throw call.Error; } if (call.StatusCode == HttpStatusCode.Unauthorized) { if (retryInvalidToken && _accessTokenProvider != null) { string newAccessToken = _accessTokenProvider().Result; if (newAccessToken != null) { _accessToken = newAccessToken; call = SendSync(request, false); } } } // Done return call; }