public SendAsync ( HttpRequestMessage request ) : Task |
||
request | HttpRequestMessage | |
return | Task |
public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location, UserAccountEntity userAccountEntity) { if (userAccountEntity.GetAccessToken().Equals("refresh")) { await Auth.RefreshAccessToken(userAccountEntity); } var param = new Dictionary<String, String>(); if (!string.IsNullOrEmpty(name)) param.Add("name", name); if (!string.IsNullOrEmpty(url)) param.Add("url", url); if (!string.IsNullOrEmpty(location)) param.Add("location", location); if (!string.IsNullOrEmpty(description)) param.Add("description", description); var theAuthClient = new HttpClient(); HttpContent header = new FormUrlEncodedContent(param); var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header}; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken()); try { HttpResponseMessage response = await theAuthClient.SendAsync(request); return response.IsSuccessStatusCode; } catch (Exception) { return false; } }
static void Main() { var address = "http://localhost:9000/"; using (WebApp.Start<Startup>(address)) { var client = new HttpClient(); PrintResponse(client.GetAsync(address + "api/items.json").Result); PrintResponse(client.GetAsync(address + "api/items.xml").Result); PrintResponse(client.GetAsync(address + "api/items?format=json").Result); PrintResponse(client.GetAsync(address + "api/items?format=xml").Result); var message1 = new HttpRequestMessage(HttpMethod.Get, address + "api/items"); message1.Headers.Add("ReturnType","json"); var message2 = new HttpRequestMessage(HttpMethod.Get, address + "api/items"); message2.Headers.Add("ReturnType", "xml"); PrintResponse(client.SendAsync(message1).Result); PrintResponse(client.SendAsync(message2).Result); Console.ReadLine(); } }
public string Translate(string text, string from, string to) { using (var client = new HttpClient()) { var url = string.Format( _translatorApiUrlFormat, HttpUtility.UrlEncode(text), HttpUtility.UrlEncode(from), HttpUtility.UrlEncode(to)); using (var message = new HttpRequestMessage(HttpMethod.Get, url)) { message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken()); using (var result = client.SendAsync(message).Result) { if (!result.IsSuccessStatusCode) { throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result); } using (var responseStream = result.Content.ReadAsStreamAsync().Result) { var serializer = new DataContractSerializer(typeof(string)); return serializer.ReadObject(responseStream) as string; } } } } }
[InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri, string expectedResult) { // Arrange CustomersModelWithInheritance model = new CustomersModelWithInheritance(); var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) }; TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers)); HttpConfiguration config = new HttpConfiguration(); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; config.Services.Replace(typeof(IAssembliesResolver), resolver); config.MapODataServiceRoute("odata", "", model.Model); HttpServer server = new HttpServer(config); config.EnsureInitialized(); HttpClient client = new HttpClient(server); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri); // Act var response = await client.SendAsync(request); // Assert if (!response.IsSuccessStatusCode) { Assert.False(true, await response.Content.ReadAsStringAsync()); } var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>(); Assert.Equal(expectedResult, result.Value); }
public void Mvc200RequestFW45BasicRequestSyntheticFiltering() { const string requestPath = "api/products"; const string expectedRequestName = "GET products"; string expectedRequestUrl = this.Config.ApplicationUri + "/" + requestPath; DateTimeOffset testStart = DateTimeOffset.UtcNow; //Call an applicaiton page var client = new HttpClient(); var requestMessage = new HttpRequestMessage { RequestUri = new Uri(expectedRequestUrl), Method = HttpMethod.Get, }; requestMessage.Headers.Add("User-Agent", "bingbot"); var responseTask = client.SendAsync(requestMessage); responseTask.Wait(TimeoutInMs); var responseTextTask = responseTask.Result.Content.ReadAsStringAsync(); responseTextTask.Wait(TimeoutInMs); Assert.IsTrue(responseTextTask.Result.StartsWith("[{")); var request = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(1, TimeoutInMs)[0]; var testFinish = DateTimeOffset.UtcNow; this.TestWebApplicationHelper(expectedRequestName, expectedRequestUrl, "200", true, request, testStart, testFinish); Assert.AreEqual("Spider", request.OperationContext.SyntheticSource); }
static void Main() { var address = "http://localhost:9000/"; using (WebApp.Start<Startup>(address)) { var client = new HttpClient(); var normalRequest = new HttpRequestMessage(HttpMethod.Get, address + "items"); Console.WriteLine(normalRequest); var normalResponse = client.SendAsync(normalRequest).Result; Console.WriteLine(normalResponse); Console.WriteLine(normalResponse.Content.ReadAsStringAsync().Result); Console.WriteLine(); Console.WriteLine(); var rangeRequest = new HttpRequestMessage(HttpMethod.Get, address + "items"); rangeRequest.Headers.Range = new RangeHeaderValue(from: 2, to: 4) { Unit = "Item" }; Console.WriteLine(rangeRequest); var rangeResponse = client.SendAsync(rangeRequest).Result; Console.WriteLine(rangeResponse); Console.WriteLine(rangeResponse.Content.ReadAsStringAsync().Result); Console.ReadLine(); } }
static void Main() { var address = "http://*****:*****@"..\..\..\textfile.txt"), Path.Combine(Assembly.GetExecutingAssembly().Location, @"..\..\..\evilfile.bat") }; using (WebApp.Start<Startup>(address)) { var client = new HttpClient(); var message1 = new HttpRequestMessage(HttpMethod.Post, address + "upload") { Content = GetContentToUpload(files) }; var result1 = client.SendAsync(message1).Result; Console.WriteLine(result1.StatusCode); Console.WriteLine(); var message2 = new HttpRequestMessage(HttpMethod.Post, address + "uploadToMemory") { Content = GetContentToUpload(files) }; var result2 = client.SendAsync(message2).Result; Console.WriteLine(result2.Content.ReadAsStringAsync().Result); Console.WriteLine(result2.StatusCode); Console.ReadLine(); } }
static void Main() { var address = "http://localhost:9000/"; using (WebApp.Start<Startup>(address)) { var client = new HttpClient(); var message1 = new HttpRequestMessage(HttpMethod.Post, address + "buffered") { Content = GetContentToUpload() }; var result1 = client.SendAsync(message1).Result; Console.WriteLine(result1.Content.ReadAsStringAsync().Result); Console.WriteLine(result1.StatusCode); Console.WriteLine(); var message2 = new HttpRequestMessage(HttpMethod.Post, address + "unbuffered") { Content = GetContentToUpload() }; var result2 = client.SendAsync(message2).Result; Console.WriteLine(result2.Content.ReadAsStringAsync().Result); Console.WriteLine(result2.StatusCode); Console.ReadLine(); } }
public async Task ItReturnsThankYouMessageOnSuccessEmail() { SetBusinessIdRequestHeader("healthystockport"); var formContents = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("Name", "Bill"), new KeyValuePair <string, string>("Email", "*****@*****.**"), new KeyValuePair <string, string>("Subject", "Test Subject"), new KeyValuePair <string, string>("Message", "Test Message"), new KeyValuePair <string, string>("ServiceEmailId", "test-email"), new KeyValuePair <string, string>("g-recaptcha-response", "test") }); var request = new HttpRequestMessage(HttpMethod.Post, "/contact-us") { Content = formContents }; request.Headers.Add("Referer", "http://something.com/a-page"); var result = await _fakeClient.SendAsync(request); result.StatusCode.Should().Be(HttpStatusCode.Redirect); result.Headers.Location.OriginalString.Should().Be("/thank-you?ReturnUrl=%2Fa-page"); }
public static async Task resetResample() { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); String url = ServerConfig.Instance.serverAddress; var resetRequest = new HttpRequestMessage(new HttpMethod("POST"), url + "/reset"); resetRequest.Headers.Add("token", "masterToken"); var resampleRequest = new HttpRequestMessage(new HttpMethod("POST"), url + "/resample"); resampleRequest.Headers.Add("token", "masterToken"); var resetResult = await client.SendAsync(resetRequest); var resampleResult = await client.SendAsync(resampleRequest); if (resetResult.StatusCode != HttpStatusCode.OK || resampleResult.StatusCode != HttpStatusCode.OK) { throw new Exception("Failed to reset/resample: " + resampleResult.StatusCode); } UserController.Instance.Logout(); ClinicianController.Instance.Logout(); }
public bool Download(Uri torrent, Uri torrenWebUiUri, string password) { using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, $"{torrenWebUiUri}login"); var formContent = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("username", "admin"), new KeyValuePair<string, string>("password", password) }; request.Content = new FormUrlEncodedContent(formContent); var responseContent = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result; if (!responseContent.Equals(SuccessAuthResponse)) { _logger.Error($"{GetType().Name}: Invalid login or password"); return false; } request = new HttpRequestMessage(HttpMethod.Post, $"{torrenWebUiUri}command/download"); formContent = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("urls", torrent.AbsoluteUri) }; request.Content = new FormUrlEncodedContent(formContent); responseContent = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result; } return true; }
static void Main() { var address = "http://localhost:9000/"; using (WebApp.Start<Startup>(address)) { var client = new HttpClient(); var meesage1 = new HttpRequestMessage(HttpMethod.Get, address + "stream/hello.html"); var response1 = client.SendAsync(meesage1).Result; Console.WriteLine(response1.Content.ReadAsStringAsync().Result); Console.WriteLine(); var meesage2 = new HttpRequestMessage(HttpMethod.Get, address + "bytearray/hello.html"); var response2 = client.SendAsync(meesage2).Result; Console.WriteLine(response2.Content.ReadAsStringAsync().Result); var meesage3 = new HttpRequestMessage(HttpMethod.Get, address + "multipart/hello.html,hello2.html"); var response3 = client.SendAsync(meesage3).Result; Console.WriteLine(response3.Content.ReadAsStringAsync().Result); Console.ReadLine(); } }
/// <summary> /// Returns the data in a block in an Amazon Elastic Block Store snapshot. /// GetSnapshotBlock /snapshots/{snapshotId}/blocks/{blockIndex}#blockToken /// </summary> /// <param name="snapshotId">The ID of the snapshot containing the block from which to get data.</param> /// <param name="blockIndex"><p>The block index of the block from which to get data.</p> <p>Obtain the <code>BlockIndex</code> by running the <code>ListChangedBlocks</code> or <code>ListSnapshotBlocks</code> operations.</p></param> /// <param name="blockToken"><p>The block token of the block from which to get data.</p> <p>Obtain the <code>BlockToken</code> by running the <code>ListChangedBlocks</code> or <code>ListSnapshotBlocks</code> operations.</p></param> /// <returns>Success</returns> public async Task <GetSnapshotBlockResponse> GetSnapshotBlockAsync(string snapshotId, int blockIndex, string blockToken, Action <System.Net.Http.Headers.HttpRequestHeaders> handleHeaders = null) { var requestUri = "/snapshots/" + (snapshotId == null? "" : Uri.EscapeDataString(snapshotId)) + "/blocks/" + blockIndex + "#blockToken&blockToken=" + (blockToken == null? "" : Uri.EscapeDataString(blockToken)); using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri)) { if (handleHeaders != null) { handleHeaders(request.Headers); } var responseMessage = await client.SendAsync(request); try { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { var serializer = new JsonSerializer(); return(serializer.Deserialize <GetSnapshotBlockResponse>(jsonReader)); } } finally { responseMessage.Dispose(); } } }
[OutputCache(Duration = 3600)] // Cache for 1 hour public virtual async Task<ActionResult> GlimpseTweets() { var key = ConfigurationManager.AppSettings["TwitterKey"]; var secret = ConfigurationManager.AppSettings["TwitterSecret"]; var bearerToken = GetBearerTokenCredentials(key, secret); var httpClient = new HttpClient(); var accessTokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token"); accessTokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", bearerToken); accessTokenRequest.Headers.Accept.ParseAdd("application/x-www-form-urlencoded;charset=UTF-8"); accessTokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "grant_type", "client_credentials" } }); var accessTokenResponse = await httpClient.SendAsync(accessTokenRequest); accessTokenResponse.EnsureSuccessStatusCode(); var jsonString = await accessTokenResponse.Content.ReadAsStringAsync(); dynamic json = JObject.Parse(jsonString); string accessToken = json.access_token; var query = "from:@nikmd23 OR from:@anthony_vdh OR from:@CGijbels #glimpse"; var searchRequest = new HttpRequestMessage(HttpMethod.Get, "https://api.twitter.com/1.1/search/tweets.json?q=" + HttpUtility.UrlEncode(query)); searchRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var searchResponse = await httpClient.SendAsync(searchRequest); searchResponse.EnsureSuccessStatusCode(); var result = await searchResponse.Content.ReadAsStringAsync(); return Content(result, "application/json"); }
protected RemoteEndpoint(string protocol, string server, int regularPort, int adminPort) { var builder = new UriBuilder(); builder.Scheme = protocol; builder.Host = server; builder.Port = regularPort; _regularUri = builder.Uri; builder.Port = adminPort; _adminUri = builder.Uri; using (var httpClient = new HttpClient()) { try { var request = new HttpRequestMessage(HttpMethod.Get, _adminUri + "/"); var response = httpClient.SendAsync(request).Result; request = new HttpRequestMessage(HttpMethod.Get, _regularUri + "/"); response = httpClient.SendAsync(request).Result; } catch(AggregateException e) { var ex = e.InnerException as WebException; if (ex != null && ex.Status == WebExceptionStatus.ConnectFailure) { Assert.Inconclusive("Failed to get connection to {0}", Type); } } } }
public async Task InvalidatesCachePerMethod() { // setup var testMessageHandler = new TestMessageHandler(); var handler = new InMemoryCacheHandler(testMessageHandler); var client = new System.Net.Http.HttpClient(handler); // execute with two methods, and clean up one cache var uri = new Uri("http://unittest"); await client.GetAsync(uri); await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri)); testMessageHandler.NumberOfCalls.Should().Be(2); // clean cache handler.InvalidateCache(uri, HttpMethod.Head); // execute both actions, and only one should be retrieved from cache await client.GetAsync(uri); await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri)); testMessageHandler.NumberOfCalls.Should().Be(3); }
static void Main() { var address = "http://localhost:9000/"; using (WebApp.Start<Startup>(address)) { var client = new HttpClient(); var message1 = new HttpRequestMessage(HttpMethod.Get, address + "test1"); var response1 = client.SendAsync(message1).Result; Console.WriteLine(response1.Content.ReadAsStringAsync().Result); Console.WriteLine(); var message2 = new HttpRequestMessage(HttpMethod.Get, address + "test2"); var response2 = client.SendAsync(message2).Result; Console.WriteLine(response2.Content.ReadAsStringAsync().Result); Console.WriteLine(); var message3 = new HttpRequestMessage(HttpMethod.Get, address + "test3"); var response3 = client.SendAsync(message3).Result; Console.WriteLine(response3.Content.ReadAsStringAsync().Result); } Console.ReadLine(); }
/// <summary> /// Provides information about a given change set. /// DescribeChangeSet /DescribeChangeSet#catalog&changeSetId /// </summary> /// <param name="catalog">Required. The catalog related to the request. Fixed value: <code>AWSMarketplace</code> </param> /// <param name="changeSetId">Required. The unique identifier for the <code>StartChangeSet</code> request that you want to describe the details for.</param> /// <returns>Success</returns> public async Task <DescribeChangeSetResponse> DescribeChangeSetAsync(string catalog, string changeSetId, Action <System.Net.Http.Headers.HttpRequestHeaders> handleHeaders = null) { var requestUri = "/DescribeChangeSet#catalog&changeSetId?catalog=" + (catalog == null? "" : Uri.EscapeDataString(catalog)) + "&changeSetId=" + (changeSetId == null? "" : Uri.EscapeDataString(changeSetId)); using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri)) { if (handleHeaders != null) { handleHeaders(request.Headers); } var responseMessage = await client.SendAsync(request); try { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { var serializer = new JsonSerializer(); return(serializer.Deserialize <DescribeChangeSetResponse>(jsonReader)); } } finally { responseMessage.Dispose(); } } }
public ElasticsearchResponse DoSyncRequest(string method, Uri uri, byte[] data = null) { var client = new System.Net.Http.HttpClient(); HttpResponseMessage response = null; byte[] result = null; HttpContent content = null; if (data != null) content = new ByteArrayContent(data); switch (method.ToLower()) { case "head": response = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri) ).Result; result = response.Content.ReadAsByteArrayAsync().Result; break; case "delete": response = client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri) { Content = content }).Result; result = response.Content.ReadAsByteArrayAsync().Result; break; case "put": response = client.PutAsync(uri, content).Result; result = response.Content.ReadAsByteArrayAsync().Result; break; case "post": response = client.PostAsync(uri, content).Result; result = response.Content.ReadAsByteArrayAsync().Result; break; case "get": response = client.GetAsync(uri).Result; result = response.Content.ReadAsByteArrayAsync().Result; break; } return ElasticsearchResponse.Create(this._settings, (int)response.StatusCode, method, uri.ToString(), data, result); }
static void Main() { var address = "http://localhost:9000/"; using (WebApp.Start<Startup>(address)) { var client = new HttpClient(); var req1 = new HttpRequestMessage(HttpMethod.Get, address + "order/1"); var res1 = client.SendAsync(req1).Result; Console.WriteLine(req1.RequestUri); Console.WriteLine(res1.Content.ReadAsStringAsync().Result); Console.WriteLine(); var req2 = new HttpRequestMessage(HttpMethod.Get, address + "auftrag/1"); var res2 = client.SendAsync(req2).Result; Console.WriteLine(req2.RequestUri); Console.WriteLine(res2.Content.ReadAsStringAsync().Result); Console.WriteLine(); var req3 = new HttpRequestMessage(HttpMethod.Get, address + "zamowienie/1"); var res3 = client.SendAsync(req3).Result; Console.WriteLine(req3.RequestUri); Console.WriteLine(res3.Content.ReadAsStringAsync().Result); Console.ReadLine(); } }
public Task <HttpResponseMessage> DeleteAsync(string uri, string authorizationToken = null, string requestId = null, string authorizationMethod = "Bearer") { var origin = GetOriginFromUri(uri); return(HttpInvoker(origin, async ctx => { var requestMessage = new HttpRequestMessage(HttpMethod.Delete, uri); SetAuthorizationHeader(requestMessage); if (authorizationToken != null) { requestMessage.Headers.Authorization = new AuthenticationHeaderValue(authorizationMethod, authorizationToken); } if (requestId != null) { requestMessage.Headers.Add("x-requestid", requestId); } return await _client.SendAsync(requestMessage); })); }
public void UserCredentialsPopsDialog() { var cache = new TestTokenCache(); var settings = ActiveDirectoryServiceSettings.Azure; var credentials = UserTokenProvider.LoginWithPromptAsync(this._domain, ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, this._username, cache).GetAwaiter().GetResult(); var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); var response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Repeat with PromptBehavior.Never credentials = UserTokenProvider.LoginWithPromptAsync(this._domain, ActiveDirectoryClientSettings.UseCacheOrCookiesOnly("1950a258-227b-4e31-a9cf-717495945fc2",new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, this._username, cache).GetAwaiter().GetResult(); request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Repeat with getting tokens strictly from cache credentials = UserTokenProvider.CreateCredentialsFromCache("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, this._username, cache).GetAwaiter().GetResult(); request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
public async Task <WebClientResponseMessage> GetAsync(WebClientRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { var httpRequestMessage = await CreateHttpRequestMessage(request, new System.Net.Http.HttpMethod(Constants.HttpMethod.GET)); var result = await _httpClient.SendAsync(httpRequestMessage, cancellationToken); return(await CreateWebClientResponseMessage(result)); }
private static void Main() { const string address = "http://localhost:925/"; var config = new HttpSelfHostConfiguration(address); config.MapHttpAttributeRoutes(); var handler = new HawkMessageHandler( async id => new HawkCredential { Id = id, Key = "abcdefghijkl", Algorithm = "sha256", User = "******" }, 4, true); config.MessageHandlers.Add(handler); using (var server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); var client = new HttpClient(); //this will fail var request = new HttpRequestMessage(HttpMethod.Get, address + "test"); var response = client.SendAsync(request).Result; Console.WriteLine(response.StatusCode); Console.WriteLine(); var credential = new HawkCredential { Id = "this-is-my-id", Key = "abcdefghijkl", Algorithm = "sha256", User = "******" }; var clientHandler = new HawkClientMessageHandler(new HttpClientHandler(), credential, ts: DateTime.Now); var client2 = new HttpClient(clientHandler); //this will succeed request = new HttpRequestMessage(HttpMethod.Get, address + "test"); var response2 = client2.SendAsync(request).Result; Console.WriteLine(response2.StatusCode); Console.WriteLine(response2.Content.ReadAsStringAsync().Result); Console.WriteLine(); Console.WriteLine("Sleeping to get outside of the timestamp window. Next request will fail - replay protection."); Thread.Sleep(5000); //this will fail request = new HttpRequestMessage(HttpMethod.Get, address + "test"); var response3 = client2.SendAsync(request).Result; Console.WriteLine(response3.StatusCode); Console.WriteLine(); Console.ReadLine(); } }
public async Task ItShouldNotAllowSameNonceTwiceIfConfigured() { var client = new System.Net.Http.HttpClient(); var signatureBodySourceBuilder = new SignatureBodySourceBuilder(); var signatureBodySigner = new HashAlgorithmSignatureBodySigner(); var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_fixture.ServerUri, ApiController.GetSignatureValidationResultGetUri)); var nonce = Guid.NewGuid().ToString(); var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var signatureBodySourceParameters = new SignatureBodySourceParameters( request.Method.ToString(), request.RequestUri, new Dictionary <string, string>(), nonce, timestamp, StartupWithMiddleware.DefaultClientId, DefaultConstants.SignatureBodySourceComponents); var signatureBodySource = await signatureBodySourceBuilder.Build(signatureBodySourceParameters); var signatureBody = await signatureBodySigner.Sign(new SignatureBodyParameters(signatureBodySource, StartupWithMiddleware.DefaultClientSecret)); var signature = $"{StartupWithMiddleware.DefaultClientId}:{nonce}:{timestamp}:{signatureBody}"; request.Headers.TryAddWithoutValidation(DefaultConstants.HeaderName, signature); var response = await client.SendAsync(request); var result = await response.Content.ReadAsAsync <SignatureValidationResult>(); result.Status.Should().Be(SignatureValidationResultStatus.OK); result.ClientId.Should().Be(StartupWithMiddleware.DefaultClientId); timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); request = new HttpRequestMessage(HttpMethod.Get, new Uri(_fixture.ServerUri, ApiController.GetSignatureValidationResultGetUri)); signatureBodySourceParameters = new SignatureBodySourceParameters( request.Method.ToString(), request.RequestUri, new Dictionary <string, string>(), nonce, timestamp, StartupWithMiddleware.DefaultClientId, DefaultConstants.SignatureBodySourceComponents); signatureBodySource = await signatureBodySourceBuilder.Build(signatureBodySourceParameters); signatureBody = await signatureBodySigner.Sign(new SignatureBodyParameters(signatureBodySource, StartupWithMiddleware.DefaultClientSecret)); signature = $"{StartupWithMiddleware.DefaultClientId}:{nonce}:{timestamp}:{signatureBody}"; request.Headers.TryAddWithoutValidation(DefaultConstants.HeaderName, signature); response = await client.SendAsync(request); result = await response.Content.ReadAsAsync <SignatureValidationResult>(); result.Status.Should().Be(SignatureValidationResultStatus.NonceHasBeenUsedBefore); }
/// <summary> /// GET方法获取 /// </summary> /// <typeparam name="TResponse"></typeparam> /// <param name="url"></param> /// <param name="token"></param> /// <param name="queryString"></param> /// <param name="userId"></param> /// <returns></returns> public async Task <TResponse> GetWithToken <TResponse>(string url, string token, NameValueCollection queryString = null, string userId = "", NameValueCollection headers = null) where TResponse : class, new() { if (queryString != null) { url = CreateUrl(url, queryString); } HttpMethod hm = new HttpMethod("GET"); var request = new HttpRequestMessage(hm, url); if (!String.IsNullOrEmpty(token)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); } if (!String.IsNullOrEmpty(userId)) { request.Headers.Add("User", userId); } if (headers != null) { var keys = headers.AllKeys; for (var i = 0; i < keys.Length; i++) { request.Headers.Add(keys[i], headers[keys[i]]); } } var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead); string str = await response.Content.ReadAsStringAsync(); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden) { throw new UnauthorizedAccessException("请求失败"); } var statusCode = (int)response.StatusCode; if (statusCode >= 300) { //throw new ApiCore.Models.RestClientException(statusCode, str); } try { if (typeof(TResponse) == typeof(string)) { return((TResponse)(object)str); } return(Newtonsoft.Json.JsonConvert.DeserializeObject <TResponse>(str)); } catch (Exception e) { throw; } }
static void Main(string[] args) { var config = new HttpConfiguration(); var builder = new ODataConventionModelBuilder(config); builder.EntitySet<Customer>("Customers"); var model = builder.GetEdmModel(); config.MapODataServiceRoute("api", "api", model); var server = new HttpServer(config); var client = new HttpClient(server); Console.WriteLine("=============Patch entity with null: \n"); dynamic delta = new JObject(); delta.FirstName = "def"; delta.LastName = null; dynamic address = new JObject(); address.Region = null; address.Street = "Lianhua"; delta.Address = address; string json = JsonConvert.SerializeObject(delta); var content = new StringContent(json, Encoding.Default, "application/json"); var request = new HttpRequestMessage(new HttpMethod("PATCH"), "http://localhost/api/Customers(0)") { Content = content, }; var response = client.SendAsync(request).Result; response.EnsureSuccessStatusCode(); var result = response.Content.ReadAsStringAsync().Result; Console.WriteLine(result); var customer = JsonConvert.DeserializeObject<Customer>(result); Debug.Assert(customer.LastName == null); Debug.Assert(customer.Address.Region == null); Console.WriteLine("\n=============Patch complex property: \n"); // Patch a complex type property is supported: See https://github.com/OData/WebApi/issues/135 address = new JObject(); address.Street = "MY"; address.City = "Paris"; address.Region = null; json = JsonConvert.SerializeObject(address); int a = json.IndexOf("{", StringComparison.Ordinal); json = json.Insert(a + 1, "\"@odata.type\":\"#PatchNull.Address\","); content = new StringContent(json, Encoding.Default, "application/json"); request = new HttpRequestMessage(new HttpMethod("PATCH"), "http://localhost/api/Customers(1)/Address") { Content = content, }; response = client.SendAsync(request).Result; response.EnsureSuccessStatusCode(); var payload = response.Content.ReadAsAsync<JObject>().Result; Console.WriteLine(payload); }
private static void Main(string[] args) { Console.WriteLine("Username:"******"Password:"******"http://localhost:3915/Account/Login"), Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("Username", username), new KeyValuePair<string, string>("Password", password) }) }; // try to authenticate var authResponse = client.SendAsync(authRequest).Result; IEnumerable<string> values; authResponse.Headers.TryGetValues("Set-Cookie", out values); if (null == values || string.IsNullOrEmpty(values.First())) { Console.WriteLine("Username and password must equal."); Console.ReadLine(); return; } var cookie = values.First(); // setup request to retrieve data from the server var request = new HttpRequestMessage() { RequestUri = new Uri("http://localhost:3915/customer/get/1") }; // assign cookie request.Headers.Add("Cookie", cookie); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.SendAsync(request).Result; Console.WriteLine("Customer: {0}", response.Content.ReadAsAsync<Customer>().Result.Name); Console.ReadLine(); }
public async Task CachesHeadAndGetRequestWithoutConflict() { var testMessageHandler = new TestMessageHandler(); var cache = new MemoryCache(new MemoryCacheOptions()); var client = new System.Net.Http.HttpClient(new InMemoryCacheHandler(testMessageHandler, null, null, cache)); // execute twice for different methods await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, "http://unittest")); await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://unittest")); // validate testMessageHandler.NumberOfCalls.Should().Be(2); }
public async Task <HttpResponse> ExecuteAsync(IHttpRequest request) { var requestMessage = BuildRequestMessage(request); try { var response = await client.SendAsync(requestMessage).ConfigureAwait(continueOnCapturedContext: false); return(await BuildResponse(response)); } catch (TaskCanceledException) { throw new HttpTimeoutException(); } }
static void Main() { var address = "http://localhost:9000/"; using (WebApp.Start<Startup>(address)) { var item = new Item() { Id = 50, Country = "Scotland", Name = "Richard" }; var client = new HttpClient(); var msg = new HttpRequestMessage(new HttpMethod("PATCH"), address + "delta/1") { Content = new ObjectContent(typeof (Item), item, new JsonMediaTypeFormatter()) }; var response = client.SendAsync(msg).Result; Print(response); var postData = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Id", 100), new KeyValuePair<string, object>("Country", "Finland"), new KeyValuePair<string, object>("Name", "Sami") }; var msgTwo = new HttpRequestMessage(new HttpMethod("PATCH"), address + "custom/2") { Content = new ObjectContent(typeof(IEnumerable<KeyValuePair<string, object>>), postData, new JsonMediaTypeFormatter()) }; var responseTwo = client.SendAsync(msgTwo).Result; Print(responseTwo); var updateItem = new Item() { Country = "Cuba", Name = "Roberto" }; var msgThree = new HttpRequestMessage(new HttpMethod("PATCH"), address + "traditional/3") { Content = new ObjectContent(typeof(Item), updateItem, new JsonMediaTypeFormatter()) }; var responseThree = client.SendAsync(msgThree).Result; Print(responseThree); Console.ReadLine(); } }
public async void postAPI(Task task) { try { Uri sUrl = new Uri(@"http://localhost:50157/api/tasks/post"); System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); //construct json var json = Newtonsoft.Json.JsonConvert.SerializeObject(task); var content = new StringContent(json, Encoding.UTF8, "application/json"); System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage { Method = System.Net.Http.HttpMethod.Post, RequestUri = sUrl, Content = content }; System.Net.Http.HttpResponseMessage response = await httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var httpResponseBody = await response.Content.ReadAsStringAsync(); Task ta = new Task(httpResponseBody); Task d = tup.Item2.Where(x => x.TaskId == ta.TaskId).Single(); d.Status = ta.Status; d.Note = ta.Note; this.Frame.Navigate(typeof(TaskIndex), tup.Item2); } catch (HttpRequestException e) { Debug.WriteLine("\nException Message : " + e.InnerException.Message); } }
/// <summary> /// Sends the specified request and returns a response. /// </summary> /// <param name="request">A <see cref="IRequest"/> that represents the HTTP request</param> /// <param name="cancellationToken">Used to cancel the request</param> /// <returns>A <see cref="Task" /> of <see cref="IResponse"/></returns> public async Task<IResponse> Send(IRequest request, CancellationToken cancellationToken) { if (request == null) throw new ArgumentNullException("request"); var httpOptions = CreateMessageHandler(); httpOptions.AllowAutoRedirect = request.AllowAutoRedirect; if (httpOptions.SupportsAutomaticDecompression) { httpOptions.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } var http = new HttpClient(httpOptions) { BaseAddress = request.BaseAddress, Timeout = request.Timeout }; using (var requestMessage = _messageBuilder.BuildRequestMessage(request)) { // Make the request var responseMessage = await http.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, cancellationToken) .ConfigureAwait(false); return await _messageBuilder.BuildResponse(responseMessage).ConfigureAwait(false); } }
private static string Request_POST(string uri, string raw) { string timeKey = System.DateTime.Now.ToString(uri + "_yyyy-MM-dd hh:mm:ss.ffff"); System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(async() => { using (var client = new System.Net.Http.HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Post, uri)) { request.Content = new System.Net.Http.StringContent(raw, Encoding.UTF8, "application/json");//CONTENT-TYPE header await client.SendAsync(request).ContinueWith(responseTask => { dicResult.Add(timeKey, responseTask.Result.Content.ReadAsStringAsync().Result); }); } })) { IsBackground = true }; th.Start(); return(timeKey); }
/// <summary> /// HttpClient请求 采用SendAsync方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestUri">请求地址</param> /// <param name="content">发送数据</param> /// <param name="httpMethod">请求方式</param> /// <returns></returns> public ResponseResult <T> HttpClientRequest <T>(string requestUri, object content, string httpMethod, WebHeaderCollection webHeaders = null, ResponseResultType resultType = ResponseResultType.ResultInfo) { try { //设置全局定义的个性化安全认证 SetDefaultHeaders(_httpItem.SecurityHeaders); //加载或者更新私定的安全认证 SetDefaultHeaders(webHeaders); var method = new HttpMethod(httpMethod); var postData = JsonConvert.SerializeObject(content); var httpContent = new StringContent(postData, Encoding.UTF8); var request = new HttpRequestMessage(method, requestUri) { Content = httpContent }; var responseResult = _client.SendAsync(request); //处理数据解析 return(JsonConvertResultData <T>(responseResult, resultType)); } catch (InvalidOperationException ex) { return(new ResponseResult <T>() { Code = (int)HttpStatusCode.BadRequest, Msg = ex.Message }); } }
public void QueryForAnEntryIncludeTheAutoExpandNavigationProperty(string url, int propCount) { // Arrange string queryUrl = string.Format(url, BaseAddress); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata.metadata=none")); HttpClient client = new HttpClient(); HttpResponseMessage response; // Act response = client.SendAsync(request).Result; // Assert Assert.NotNull(response); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Content); var customer = response.Content.ReadAsAsync<JObject>().Result; Assert.Equal(customer.Properties().Count(), propCount); VerifyOrderAndChoiceOrder(customer); // level one JObject friend = customer["Friend"] as JObject; VerifyOrderAndChoiceOrder(friend); // level two Assert.Null(friend["Friend"]); }
public async Task<BitmapImage> GetPhotoAsync(string photoUrl, string token) { using (var client = new HttpClient()) { try { var request = new HttpRequestMessage(HttpMethod.Get, new Uri(photoUrl)); BitmapImage bitmap = null; request.Headers.Add("Authorization", "Bearer " + token); var response = await client.SendAsync(request); var stream = await response.Content.ReadAsStreamAsync(); if (response.IsSuccessStatusCode) { using (var memStream = new MemoryStream()) { await stream.CopyToAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } return bitmap; } else { Debug.WriteLine("Unable to find an image at this endpoint."); bitmap = new BitmapImage(new Uri("ms-appx:///assets/UserDefault.png", UriKind.RelativeOrAbsolute)); return bitmap; } } catch (Exception e) { Debug.WriteLine("Could not get the thumbnail photo: " + e.Message); return null; } } }
public async static Task Sync_mstr_menu_master() { try { HttpClient httpClient = new System.Net.Http.HttpClient(); httpClient.Timeout = TimeSpan.FromMinutes(20); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Library.URL + "/" + Library.METHODE_NENU_MASETER + "/" + Library.KEY_USER_ccode + "/" + Library.KEY_USER_regcode + "/" + Library.KEY_USER_siteid + "/0"); HttpResponseMessage response = await httpClient.SendAsync(request); // jarray= await response.Content.ReadAsStringAsync(); List <mstr_menu_master> jarray = JsonConvert.DeserializeObject <List <mstr_menu_master> >(await response.Content.ReadAsStringAsync()); using (var dbConn = DependencyService.Get <IDBInterface>().GetConnection()) { dbConn.DropTable <mstr_menu_master>(); dbConn.CreateTable <mstr_menu_master>(); dbConn.BeginTransaction(); dbConn.InsertAll(jarray); _viewModel.CurrentProgress = _viewModel.CurrentProgress + 0.5f; dbConn.Commit(); }; } catch (Exception) { } }
public async Task<ActionResult> Index(string startLetter) { List<Person> people = new List<Person>(); if (startLetter != null) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); string accessToken = spContext.UserAccessTokenForSPHost; StringBuilder requestUri = new StringBuilder() .Append(spContext.SPHostUrl) .Append("/_api/search/query?querytext='LastName:") .Append(startLetter) .Append("*'&selectproperties='LastName,FirstName,WorkEmail,WorkPhone'&sourceid='B09A7990-05EA-4AF9-81EF-EDFAB16C4E31'&sortlist='FirstName:ascending'"); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri.ToString()); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); XElement root = XElement.Parse(responseString); XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices"; foreach (XElement row in root.Descendants(d + "Rows").First().Elements(d + "element")) { Person person = new Person(); foreach (XElement cell in row.Descendants(d + "Cells").First().Elements(d + "element")) { if (cell.Elements(d + "Key").First().Value == "FirstName") { person.FirstName = cell.Elements(d + "Value").First().Value; } if (cell.Elements(d + "Key").First().Value == "LastName") { person.LastName = cell.Elements(d + "Value").First().Value; } if (cell.Elements(d + "Key").First().Value == "WorkPhone") { person.WorkPhone = cell.Elements(d + "Value").First().Value; } if (cell.Elements(d + "Key").First().Value == "WorkEmail") { person.WorkEmail = cell.Elements(d + "Value").First().Value; } } people.Add(person); } } return View(people); }
public static async Task <ServerCertificate> GetServerCertificate(Uri uri) { ServerCertificate _tmpResponseResult = null; var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = ( HttpRequestMessage requestMessage, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslErrors) => { _tmpResponseResult = new ServerCertificate(new X509Certificate2(certificate), sslErrors); return(sslErrors == SslPolicyErrors.None); } }; // TODO: avoid using using (var httpClient = new System.Net.Http.HttpClient(handler)) { httpClient.Timeout = TimeSpan.FromSeconds(60); _tmpResponseResult = null; await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri)); } return(_tmpResponseResult); }
private async static Task Sync_mstr_allergies_master() { try { HttpClient httpClient = new System.Net.Http.HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Library.URL + "/" + Library.METHODE_ALLERGENTDIETLIST + "/" + Library.KEY_USER_ccode); HttpResponseMessage response = await httpClient.SendAsync(request); // jarray= await response.Content.ReadAsStringAsync(); List <mstr_allergies_master> jarray = JsonConvert.DeserializeObject <List <mstr_allergies_master> >(await response.Content.ReadAsStringAsync()); using (var dbConn = DependencyService.Get <IDBInterface>().GetConnection()) { dbConn.DropTable <mstr_allergies_master>(); dbConn.CreateTable <mstr_allergies_master>(); dbConn.BeginTransaction(); dbConn.InsertAll(jarray); dbConn.Commit(); }; _viewModel.CurrentProgress = _viewModel.CurrentProgress + 0.06f; } catch (Exception excp) { } }
/// <summary> /// Sends the <see cref="HttpRequestMessage"/> instance. /// </summary> /// <param name="httpClient"><see cref="System.Net.Http.HttpClient"/> instance.</param> /// <param name="request"><see cref="HttpRequestMessage"/> instance.</param> /// <param name="validator"><see cref="ISchemaValidator"/> instance.</param> /// <param name="path">Schema path.</param> /// <param name="cancellationToken"><see cref="CancellationToken"/> instance.</param> /// <returns>Returns <see cref="HttpResponseMessage"/> instance.</returns> public static async Task <HttpResponseMessage> SendAsync(this System.Net.Http.HttpClient httpClient, HttpRequestMessage request, ISchemaValidator validator, string path, CancellationToken cancellationToken) { httpClient.ThrowIfNullOrDefault(); request.ThrowIfNullOrDefault(); cancellationToken.ThrowIfNullOrDefault(); validator.ThrowIfNullOrDefault(); path.ThrowIfNullOrWhiteSpace(); if (!request.Method.IsSupported()) { return(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } if (request.Method != HttpMethod.Get) { await ValidateAsync(request, validator, path).ConfigureAwait(false); } var response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); if (request.Method == HttpMethod.Get) { await ValidateAsync(response, validator, path).ConfigureAwait(false); return(response); } return(response); }
public async Task OnGet() { this.Title = "Add User"; if (Request.Query["Id"].Any()) { string id = Request.Query["Id"][0]; this.Title = "Edit User"; // get user using (var client = new System.Net.Http.HttpClient()) { var request = new System.Net.Http.HttpRequestMessage(); request.RequestUri = new Uri("http://localhost:62610/usersapi/User/" + id); var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { var model = JsonConvert.DeserializeObject <UserDTO>(await response.Content.ReadAsStringAsync()); this.User = new UserDTO(); this.User.Id = model.Id; this.User.Name = model.Name; this.User.Surname = model.Surname; this.User.Email = model.Email; this.User.BirthDate = model.BirthDate; } } } }
public async Task <HttpResponseMessage> SendAsync() { // Setup request var request = new HttpRequestMessage { Method = this.method, RequestUri = new Uri(this.requestUri) }; if (this.content != null) { request.Content = this.content; } if (!string.IsNullOrEmpty(this.bearerToken)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.bearerToken); } request.Headers.Accept.Clear(); if (!string.IsNullOrEmpty(this.acceptHeader)) { request.Headers.Accept.Add( new MediaTypeWithQualityHeaderValue(this.acceptHeader)); } // Setup client var client = new System.Net.Http.HttpClient(); client.Timeout = this.timeout; return(await client.SendAsync(request)); }
public async Task<User> createUser(User newUser) { User current= new User(); try { var encapsulated = new { user = newUser }; var jsonBodyString = JsonConvert.SerializeObject(encapsulated); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, APIConstants.Users); message.Headers.Authorization = new AuthenticationHeaderValue("Token", $"token={APIConstants.Token}"); message.Content = new StringContent(jsonBodyString, Encoding.UTF8, "application/json"); var response = await client.SendAsync(message); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); current = JsonConvert.DeserializeObject<User>(jsonString); setCurrentUser(current); } } catch (Exception e) { string error = e.Message; } return current; }
private static async Task <ConversationItemModel> QueryQnABot(string Query) { ConversationItemModel QnAQueryResult = new ConversationItemModel(); using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { string RequestURI = String.Format("{0}{1}", "https://wispero.azurewebsites.net/qnamaker", "/knowledgebases/0e778adf-9dad-4c40-8199-78cf7d3a69ca/generateAnswer"); var httpContent = new StringContent($"{{\"question\": \"{Query}\"}}", Encoding.UTF8, "application/json"); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, RequestURI); httpRequestMessage.Headers.Add("Authorization", "EndpointKey ba505028-2b0b-4630-a8e5-d32a04efdb6a"); httpRequestMessage.Content = httpContent; var msg = await client.SendAsync(httpRequestMessage); if (msg.IsSuccessStatusCode) { var JsonDataResponse = await msg.Content.ReadAsStringAsync(); var response = JsonConvert.DeserializeObject <QnAResponse>(JsonDataResponse); QnAQueryResult.Question = Query; QnAQueryResult.Answer = response.Answers.FirstOrDefault()?.Answer; } } return(QnAQueryResult); }
public static void Main(string[] args) { using (var client = new HttpClient() { BaseAddress = new Uri("http://localhost:21607/") }) { foreach (var patchData in PatchData) { using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), "/api/Patch")) { Console.WriteLine("Sending: {0}", patchData); Console.WriteLine(); request.Content = new StringContent(patchData, Encoding.UTF8, "application/json"); using (var response = client.SendAsync(request).Result) { response.EnsureSuccessStatusCode(); var responseText = response.Content.ReadAsStringAsync().Result; Console.WriteLine(responseText); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); } } } } Console.WriteLine("Press ENTER to exit..."); Console.ReadLine(); }
public async Task <IActionResult> InterestCalculation([FromQuery] decimal valorinicial, double meses) { using var client = new System.Net.Http.HttpClient(); { var request = new System.Net.Http.HttpRequestMessage(); request.RequestUri = new Uri("https://localhost:55002/taxaJuros"); var response = await client.SendAsync(request); return(Ok(await response.Content.ReadAsStringAsync())); } decimal finalValue; try { var response = await Client.GetAsync("https://localhost:55002/taxaJuros"); var responseBody = await response.Content.ReadAsStringAsync(); double.TryParse(responseBody, out var feeRate); finalValue = decimal.Multiply(valorinicial, (decimal)Math.Pow((1 + feeRate), meses)); } catch (Exception e) { Console.WriteLine(e); throw; } return(Ok(finalValue)); }
private static string GetAccessTokenClietCredentialsUsingForm() { //Request for access token using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, Paths.AuthorizationServerBaseAddress + Paths.TokenPath); var clientCredentialsRequestElements = CreateRequestResourceOwnerPasswordElements( Clients.Client1.Id, Clients.Client1.Secret, "bob", //user name "bob", //password // this is grant type "password", "read write"); request.Content = new FormUrlEncodedContent(clientCredentialsRequestElements); var response = client.SendAsync(request).Result; var payload = JObject.Parse(response.Content.ReadAsStringAsync().Result); return payload.SelectToken("access_token").ToString(); } }
private async void HandleSessionExpired(object sender, EventArgs e) { if (CrossConnectivity.Current.IsConnected) { if (!string.IsNullOrEmpty(Library.KEY_USER_ID)) { try { using (var httpClient = new System.Net.Http.HttpClient()) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Library.URL + "/updatelogfalse/" + Library.KEY_USER_ID); await httpClient.SendAsync(request); Library.KEY_USER_ID = string.Empty; } } catch (Exception) { } } } SessionManager.Instance.EndTrackSession(); await pageDialog.DisplayAlertAsync("Alert !!", "Your session has expired. Please login again.", "OK"); await NavigationService.NavigateAsync("app:///LoginPage"); }
public bool CancelAppointment(HackExchangeContext context, CalendarItem appointment) { var url = context.Endpoint; var request = new HttpRequestMessage(HttpMethod.Post, url); var postBodyTemplate = LoadXml("CancelAppointment"); var postBody = string.Format(postBodyTemplate, appointment.Id, appointment.ChangeKey); request.Content = new StringContent(postBody, Encoding.UTF8, "text/xml"); var clientHandler = new HttpClientHandler() { Credentials = context.Credentials }; using (var client = new HttpClient(clientHandler)) { var response = client.SendAsync(request).Result; var responseBody = response.Content.ReadAsStringAsync().Result; var doc = new XPathDocument(new StringReader(responseBody)); var nav = doc.CreateNavigator(); var nsManager = new XmlNamespaceManager(nav.NameTable); nsManager.AddNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages"); nsManager.AddNamespace("t", "http://schemas.microsoft.com/exchange/services/2006/types"); var responseClass = EvaluateXPath(nav, nsManager, "//m:DeleteItemResponseMessage/@ResponseClass"); return responseClass == "Success"; } }
private async Task <IHttpResponse> SendAsync(IHttpRequest request, HttpMethod httpMethod) { var clientHandler = new HttpClientHandler(); using (var client = new System.Net.Http.HttpClient(clientHandler)) { var httpRequest = new HttpRequestMessage { Method = httpMethod, RequestUri = request.Uri }; SetServerSSLSecurity(request, clientHandler); SetTimeout(request, client); SetContent(request, httpMethod, httpRequest); SetHeaders(request, httpRequest); this.log.Debug("Sending request", () => new { httpMethod, request.Uri, request.Options }); try { using (var response = await client.SendAsync(httpRequest)) { if (request.Options.EnsureSuccess) { response.EnsureSuccessStatusCode(); } return(new HttpResponse { StatusCode = response.StatusCode, Headers = response.Headers, Content = await response.Content.ReadAsStringAsync(), }); } } catch (HttpRequestException e) { var errorMessage = e.Message; if (e.InnerException != null) { errorMessage += " - " + e.InnerException.Message; } this.log.Error("Request failed", () => new { ExceptionMessage = e.Message, InnerExceptionType = e.InnerException != null ? e.InnerException.GetType().FullName : "", InnerExceptionMessage = e.InnerException != null ? e.InnerException.Message : "", errorMessage }); return(new HttpResponse { StatusCode = 0, Content = errorMessage }); } } }
public async static Task<bool> Ping(ConnectionItem connectionItem) { JObject requestObject = new JObject( new JProperty("jsonrpc", "2.0"), new JProperty("id", 234), new JProperty("method", "JSONRPC.ping")); string requestData = requestObject.ToString(); HttpClientHandler handler = new HttpClientHandler(); HttpClient httpClient = new HttpClient(handler); string uriString = "http://" + connectionItem.IpAddress + ":" + connectionItem.Port.ToString() + "/jsonrpc?request="; httpClient.BaseAddress = new Uri(uriString); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ""); request.Content = new StringContent(requestData); request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //Required to be recognized as valid JSON request. HttpResponseMessage response = await httpClient.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); if (responseString.Length == 0) return false; dynamic responseObject = JObject.Parse(responseString); bool isSuccessful = responseObject.result == "pong"; return isSuccessful; }
/// <summary> /// https://open.1688.com/solution/solutionDetail.htm?spm=0.$!pageSpm.0.0.589355edXjTGA8&solutionKey=1513248184893&category=SupplyCore#apiAndMessageList /// </summary> /// <returns></returns> public async Task <Datum[]> GetSolutionApiAndMessageListDetail() { //var response = await _httpClient.GetAsync($"https://open.1688.com/solution/data/getSolutionDetail.jsonp?solutionKey=1513248184893&callback=jsonp"); var message = new HttpRequestMessage(HttpMethod.Get, $"https://open.1688.com/solution/data/getSolutionDetail.jsonp?solutionKey=1513248184893&callback=jsonp"); message.Headers.Referrer = new System.Uri("https://open.1688.com/solution/solutionDetail.htm?solutionKey=1513248184893"); var response = await _httpClient.SendAsync(message); var result1 = await response.Content.ReadAsStringAsync(); var ss = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(result1.Remove(0, 5).Trim('(', ')')); var ddjson = ss.SelectToken("$.result.solutionDescList[?(@subCategory=='apiAndMessageList')].content").ToObject <string>(); var ss1 = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(ddjson); var ss2 = ss1.SelectTokens("$.apis[*].modules[*]"); var result = ss2.Select(f => new Datum { //description = f.Value<string>("description"), //fullName = f.Value<string>("fullName"), Name = f.Value <string>("name"), Namespace = f.Value <string>("namespace"), Version = f.Value <int>("version") }).ToArray(); return(result); }
public async Task <HttpResponseMessage> SendAsync(System.Net.Http.HttpClient client) { // Check required arguments EnsureArguments(); // Set up request var request = new HttpRequestMessage(this.method, this.requestUri); if (this.content != null) { request.Content = this.content; } if (!string.IsNullOrEmpty(this.bearerToken)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.bearerToken); } request.Headers.Accept.Clear(); if (!string.IsNullOrEmpty(this.acceptHeader)) { request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(this.acceptHeader)); } return(await client.SendAsync(request)); }
private async Task <HttpResponseMessage> SendAsync() { try { var request = new HttpRequestMessage() { Method = this.method, RequestUri = new Uri(this.requestUri) }; request.Content = this.content; request.Headers.Accept.Clear(); if (!string.IsNullOrEmpty(this.acceptHeader)) { request.Headers.Accept.Add( new MediaTypeWithQualityHeaderValue(this.acceptHeader)); } // Setup client var client = new System.Net.Http.HttpClient(); return(await client.SendAsync(request)); } catch (Exception) { throw; } }
public async Task<IList<JeuForain>> GetJeuxForainsAsync() { try { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, JEUXFORAINSURL); HttpClient httpClient = new HttpClient(); HttpResponseMessage httpResponse = await httpClient.SendAsync(request); string content = await httpResponse.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(content)) { var json = JObject.Parse(content); var records = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIJeuxForainsRecord>>(json["records"].ToString()); IList<JeuForain> values = new List<JeuForain>(); foreach (var jeux in records) values.Add(jeux.Value); return values; } } catch (Exception ex) { Debug.WriteLine("GetJeuxForainsAsync : " + ex); } return null; }
public async Task <HttpResponseMessage> GetAsync(Uri requestUri, string contentType = Constants.ContentTypeValue) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); return(await _httpClient.SendAsync(requestMessage)); }
/// <summary> /// Make an asynchronous request /// </summary> /// <param name="request">Twilio response</param> /// <returns>Task that resolves to the response</returns> public override async Task <Response> MakeRequestAysnc(Request request) { var httpRequest = BuildHttpRequest(request); if (!Equals(request.Method, HttpMethod.Get)) { httpRequest.Content = new FormUrlEncodedContent(request.PostParams); } HttpResponseMessage response = null; try { response = await _httpClient.SendAsync(httpRequest).ConfigureAwait(false); var reader = new StreamReader(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); return(new Response(response.StatusCode, await reader.ReadToEndAsync().ConfigureAwait(false))); } catch (AggregateException ae) { if (ae.InnerExceptions.OfType <HttpRequestException>().Any() && response != null) { throw await HandleErrorResponse(response).ConfigureAwait(false); } } return(null); }
private async static Task Sync_mstr_ward_details() { try { HttpClient httpClient = new System.Net.Http.HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Library.URL + "/" + Library.METHODE_DISPLAYWARDDETAILS + "/" + Library.KEY_USER_ccode + "/" + Library.KEY_USER_regcode + "/" + Library.KEY_USER_siteid + "/0"); HttpResponseMessage response = await httpClient.SendAsync(request); List <mstr_ward_details> jarray = JsonConvert.DeserializeObject <List <mstr_ward_details> >(await response.Content.ReadAsStringAsync()); using (var dbConn = DependencyService.Get <IDBInterface>().GetConnection()) { dbConn.DropTable <mstr_ward_details>(); dbConn.CreateTable <mstr_ward_details>(); dbConn.BeginTransaction(); foreach (var item in jarray) { string cont_id = item.country_id.ToString(); string rgn_id = item.region_id.ToString(); string st_id = item.site_id.ToString(); if (Library.KEY_USER_ccode == cont_id && (Library.KEY_USER_regcode == "nil" || Convert.ToInt16(Library.KEY_USER_regcode) == 0 || Library.KEY_USER_regcode == rgn_id) && (Library.KEY_USER_siteid == "nil" || Convert.ToInt32(Library.KEY_USER_siteid) == 0 || Library.KEY_USER_siteid == st_id)) { dbConn.Insert(item); } } dbConn.Commit(); _viewModel.CurrentProgress = _viewModel.CurrentProgress + 0.06f; }; } catch (Exception excp) { } }