private async void Button_Click(object sender, RoutedEventArgs e) { if (CountryPhoneCode.SelectedItem != null) { var _id = Guid.NewGuid().ToString("N"); var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode; var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName; var _name = FullName.Text; var _phoneNumber = PhoneNumber.Text; var _password = Password.Password; var client = new HttpClient() { BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/") }; var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password="******"&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode); var serializer = new DataContractJsonSerializer(typeof(User)); var ms = new MemoryStream(); var user = serializer.ReadObject(ms) as User; Frame.Navigate(typeof(MainPage), user); } else { MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!"); await dialog.ShowAsync(); } }
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); }
private async void ButtonAccessResource_Click(object sender, RoutedEventArgs e) { var client = new HttpClient { BaseAddress = _baseAddress }; if (_credential != null) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _credential.AccessToken); } var response = await client.GetAsync("identity"); if (response.StatusCode != System.Net.HttpStatusCode.OK) { var md = new MessageDialog(response.ReasonPhrase); await md.ShowAsync(); return; } var claims = await response.Content.ReadAsAsync<IEnumerable<ViewClaim>>(); foreach (var claim in claims) { ListClaims.Items.Add(string.Format("{0}: {1}", claim.Type, claim.Value)); } }
/// <summary> /// 非同步刷新最新資訊 /// </summary> /// <returns></returns> public async Task RefreshAsync() { HttpClient client = new HttpClient(); HtmlDocument HTMLDoc = new HtmlDocument(); HTMLDoc.LoadHtml(await client.GetStringAsync(DataSource)); var script = HTMLDoc.DocumentNode.Descendants("script") .Where(x => x.InnerHtml?.Length > 0).Select(x => x.InnerHtml).ToArray(); var tempAry = script.First() .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select((x, i) => new { index = i, item = x }) .GroupBy(x => Math.Floor(x.index / 4.0)); this.LastPassed = null; this.Delay = new TimeSpan(); foreach (var item in tempAry) { string[] temp = item.Select(x=>x.item).ToArray(); if(temp[3] == "TRSearchResult.push('x')") { this.LastPassed = await Station.GetStationByNameAsync( innerString(temp[0],"'","'") ); } } var time = new TimeSpan(0, int.Parse(innerString(script.Last(), "=", ";")),0); this.Delay= time; }
public ActionResult About(string searchString) { if(searchString=="" || searchString==null) { searchString = "Jurasic Park"; } List<Movie> mo = new List<Movie>(); string responseString = ""; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:51704/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("api/movie?name=" + searchString).Result; if (response.IsSuccessStatusCode) { responseString = response.Content.ReadAsStringAsync().Result; } } string jsonInput=responseString; // System.Console.Error.WriteLine(responseString); JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); mo= jsonSerializer.Deserialize<List<Movie>>(jsonInput); return View(mo); }
/// <summary> /// Restituisce i dati dell'utente /// </summary> public static async Task<Microsoft.Graph.User> GetMyInfoAsync() { //JObject jResult = null; try { HttpClient client = new HttpClient(); var token = await OfficeHelper.GetTokenAsync(); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); // Endpoint dell'utente loggato Uri usersEndpoint = new Uri($"{serviceEndpoint}me"); HttpResponseMessage response = await client.GetAsync(usersEndpoint); if (response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); return Newtonsoft.Json.JsonConvert.DeserializeObject<Microsoft.Graph.User>(responseContent); } else { var msg = new MessageDialog("Non è stato possibile recuperare i dati dell'utente. Risposta del server: " + response.StatusCode); await msg.ShowAsync(); return null; } } catch (Exception e) { var msg = new MessageDialog("Si è verificato il seguente errore: " + e.Message); await msg.ShowAsync(); return null; } }
public void FakeServer_CapturesAllRequests() { using (var fakeServer = new FakeServer()) { fakeServer.Start(); var baseAddress = fakeServer.BaseUri; Action<Action, int> repeat = (a, times) => { for (var i = 0; i < times; i++) a(); }; var url1 = "/request1"; var url2 = "/request2"; var url3 = "/request3"; var url4 = "/request4"; var httpClient = new HttpClient(); httpClient.DeleteAsync(new Uri(baseAddress + url1)).Wait(); repeat(() => httpClient.GetAsync(new Uri(baseAddress + url2)).Wait(), 2); repeat(() => httpClient.PostAsync(new Uri(baseAddress + url3), new StringContent(url3)).Wait(), 3); repeat(() => httpClient.PutAsync(new Uri(baseAddress + url4), new StringContent(url4)).Wait(), 4); fakeServer.CapturedRequests.Count(x => x.Method == Http.Delete && x.Url == url1).Should().Be(1); fakeServer.CapturedRequests.Count(x => x.Method == Http.Get && x.Url == url2).Should().Be(2); fakeServer.CapturedRequests.Count(x => x.Method == Http.Post && x.Url == url3 && x.Body == url3).Should().Be(3); fakeServer.CapturedRequests.Count(x => x.Method == Http.Put && x.Url == url4 && x.Body == url4).Should().Be(4); } }
public void Create_New_Customer() { Uri baseAddress = new Uri("http://localhost:8080/"); CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress); using (host) { host.Open(); HttpClient client = new HttpClient(baseAddress); client.Channel = new WebRequestChannel(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers"); request.Content = new StringContent("Id = 7; Name = NewCustomer7"); HttpResponseMessage response = client.Send(request); using (response) { Assert.IsNotNull(response, "The response should not have been null."); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, "The status code should have been 'Created'."); Assert.IsNotNull(response.Headers.Location, "The location header should not have been null."); Assert.AreEqual(new Uri("http://localhost:8080/Customers?id=7"), response.Headers.Location, "The location header should have beeen 'http://localhost:8080/Customers?id=7'."); Assert.AreEqual("Id = 7; Name = NewCustomer7", response.Content.ReadAsString(), "The response content should have been 'Id = 7; Name = NewCustomer7'."); } // Put server back in original state request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=7"); client.Send(request); } }
static void Main(string[] args) { var address = "http://localhost:900"; var config = new HttpSelfHostConfiguration(address); config.MapHttpAttributeRoutes(); using (var server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Server running at {0}. Press any key to exit", address); var client = new HttpClient() {BaseAddress = new Uri(address)}; var persons = client.GetAsync("person").Result; Console.WriteLine(persons.Content.ReadAsStringAsync().Result); var newPerson = new Person {Id = 3, Name = "Luiz"}; var response = client.PostAsJsonAsync("person", newPerson).Result; if (response.IsSuccessStatusCode) { var person3 = client.GetAsync("person/3").Result; Console.WriteLine(person3.Content.ReadAsStringAsync().Result); } Console.ReadLine(); } }
/// <summary> /// Does setup of AutoCAD IO. /// This method will need to be invoked once before any other methods of this /// utility class can be invoked. /// </summary> /// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param> /// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param> public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret) { try { String clientId = autocadioclientid; String clientSecret = autocadioclientsecret; Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/"); container = new AIO.Operations.Container(uri); container.Format.UseJson(); using (var client = new HttpClient()) { var values = new List<KeyValuePair<string, string>>(); values.Add(new KeyValuePair<string, string>("client_id", clientId)); values.Add(new KeyValuePair<string, string>("client_secret", clientSecret)); values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials")); var requestContent = new FormUrlEncodedContent(values); var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result; var responseContent = response.Content.ReadAsStringAsync().Result; var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent); _accessToken = resValues["token_type"] + " " + resValues["access_token"]; if (!string.IsNullOrEmpty(_accessToken)) { container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken); } } } catch (System.Exception ex) { Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message)); container = null; throw; } }
private static void SendImageSet(ImageSet imageSet) { var multipartContent = new MultipartFormDataContent(); var imageSetJson = JsonConvert.SerializeObject(imageSet, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); multipartContent.Add(new StringContent(imageSetJson, Encoding.UTF8, "application/json"), "imageset"); int counter = 0; foreach (var image in imageSet.Images) { var imageContent = new ByteArrayContent(image.ImageData); imageContent.Headers.ContentType = new MediaTypeHeaderValue(image.MimeType); multipartContent.Add(imageContent, "image" + counter++, image.FileName); } var response = new HttpClient() .PostAsync("http://localhost:53908/api/send", multipartContent) .Result; var responseContent = response.Content.ReadAsStringAsync().Result; Trace.Write(responseContent); }
/// <summary> /// BETA Create a section group with a given name under a given notebookId /// </summary> /// <param name="debug">Run the code under the debugger</param> /// <param name="notebookId">parent notebook's Id</param> /// <param name="sectionName">name of the section group to create</param> /// <param name="provider"></param> /// <param name="apiRoute"></param> /// <remarks>Create section group using a application/json content type</remarks> /// <returns>The converted HTTP response message</returns> public static async Task<ApiBaseResponse> CreateSectionGroupInNotebook(bool debug, string notebookId, string sectionGroupName, AuthProvider provider, string apiRoute) { if (debug) { Debugger.Launch(); Debugger.Break(); } var client = new HttpClient(); // Note: API only supports JSON response. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken(provider)); // Prepare an HTTP POST request to the SectionGroups endpoint // The request body content type is application/json and requires a name property var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"notebooks/" + notebookId + "/sectiongroups") { Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionGroupName) + "' }", Encoding.UTF8, "application/json") }; HttpResponseMessage response = await client.SendAsync(createMessage); return await HttpUtils.TranslateResponse(response); }
private async void UpdateContributors() { try { var vms = await Task.Run(async () => { var hc = new HttpClient(); var str = await hc.GetStringAsync(App.ContributorsUrl); using (var sr = new StringReader(str)) { var xml = XDocument.Load(sr); return xml.Root .Descendants("contributor") .Where( e => e.Attribute("visible") == null || e.Attribute("visible").Value.ToLower() != "false") .Select(ContributorsViewModel.FromXml) .ToArray(); } }); await DispatcherHelper.UIDispatcher.InvokeAsync( () => { this.Contributors.Clear(); this.Contributors.Add(new ContributorsViewModel("thanks to:", null)); vms.OrderBy(v => v.ScreenName ?? "~" + v.Name) .ForEach(this.Contributors.Add); }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
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; }
private void Initalize() { // Limit to maximum of 256 Connections ServicePointManager.DefaultConnectionLimit = 256; //Trust all certificates ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); // TODO: Add Proxy Support Handler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = true, CookieContainer = new CookieContainer(), UseDefaultCredentials = false, Proxy = null, UseProxy = false }; // Create the HTTP Client Client = new HttpClient(Handler); Client.DefaultRequestHeaders.Clear(); Client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromSeconds(0) }; Client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); Client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); }
public static async Task<string> LoadDataFromAPI(string apiAddress) { //method to check if user is authenticated and has valid details // if invalid details, response message will return unauthorised var rawAuthInfo = App.validAuthDetails; var authDetails = JsonConvert.DeserializeObject<ValidAuth>(rawAuthInfo); var rawData = ""; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authDetails.token_type, authDetails.access_token); HttpResponseMessage ResponseMsg = await httpClient.GetAsync(apiAddress); // check to see if request was successful or not if (ResponseMsg.StatusCode == System.Net.HttpStatusCode.OK) { rawData = await ResponseMsg.Content.ReadAsStringAsync(); } else if (ResponseMsg.StatusCode == System.Net.HttpStatusCode.Unauthorized) { rawData = "AuthInvalid"; } return rawData; }
public static HttpResponseMessage HttpGet(Uri uri) { using (var client = new HttpClient()) { return client.GetAsync(uri).Result; } }
public async void Run() { var httpClient = new HttpClient(); HttpResponseMessage response = null; try { response = await httpClient.GetAsync(_uri, _cancellationTokenSource.Token); var remoteStream = await response.Content.ReadAsStreamAsync(); var localStream = await _file.OpenAsync(FileAccess.ReadAndWrite); //response.Content.Headers.ContentLength; } catch (Exception ex) { if(Error != null) Error(this, new DownloadFileErrorArgs(ex, _file)); } finally { if(response != null) response.Dispose(); } }
public ActionResult DetailMovie(string movieId,string youTubeId) { if (youTubeId == "" || youTubeId == null) { youTubeId = ""; } DetailMovie movie = new Models.DetailMovie(); string responseString = ""; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:51704/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("api/movie?IMDBid=" + movieId + "&YouTubeid=" + youTubeId).Result; if (response.IsSuccessStatusCode) { responseString = response.Content.ReadAsStringAsync().Result; } } string jsonInput = responseString; // System.Console.Error.WriteLine(responseString); JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); movie = jsonSerializer.Deserialize<DetailMovie>(jsonInput); return View(movie); }
public List<Crime> FetchCrimesNearLocation(Location location) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(AllStreetCrimesUri); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); string uriQuerystring = string.Format("?date=2013-07&lat={0}&lng={1}", location.Latitude, location.Longitude ); HttpResponseMessage response = client.GetAsync(uriQuerystring).Result; if (response.IsSuccessStatusCode) { var crimes = response.Content.ReadAsAsync<IEnumerable<Crime>>().Result; return crimes.ToList(); } else { throw new Exception( string.Format("{0} ({1})", (int) response.StatusCode, response.ReasonPhrase)); } } }
private static async Task GetPeople(string address) { var uriBuilder = new UriBuilder(address); uriBuilder.Path = "api/Customer"; using (var client = new HttpClient()) { Console.WriteLine("Getting data without a version..."); var response = await client.GetAsync(uriBuilder.Uri); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); Console.WriteLine(); Console.WriteLine("Getting data for v1..."); client.DefaultRequestHeaders.Add("api-version", "1"); response = await client.GetAsync(uriBuilder.Uri); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); Console.WriteLine(); Console.WriteLine("Getting data for v2..."); client.DefaultRequestHeaders.Remove("api-version"); client.DefaultRequestHeaders.Add("api-version", "2"); response = await client.GetAsync(uriBuilder.Uri); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); Console.WriteLine(); } }
public static HttpClient CreateHttpClient() { var baseAddress = new Uri("http://localhost:8080"); var config = new HttpSelfHostConfiguration(baseAddress); // ? Setup.Configure(config); var server = new HttpSelfHostServer(config); var client = new HttpClient(server); // <--- MAGIC! try { client.BaseAddress = baseAddress; return client; } catch { client.Dispose(); throw; } }
public async Task<string> TryDownloadPackageFromFeed(string packageId, string version) { try { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { string requestUri = UrlHelper.V2FeedRootUrl + @"Package/" + packageId + @"/" + version; var response = await client.GetAsync(requestUri).ConfigureAwait(false); //print the header WriteLine("HTTP status code : {0}", response.StatusCode); WriteLine("HTTP header : {0}", response.Headers); if (response.StatusCode == HttpStatusCode.Found) { return response.Headers.GetValues("Location").FirstOrDefault(); } else { return null; } } } catch (HttpRequestException hre) { WriteLine("Exception : {0}", hre.Message); return null; } }
public GeciMeClient() { _httpClient = new HttpClient() { BaseAddress = new Uri("http://geci.me/api/lyric/") }; }
static void Main(string[] args) { Console.WriteLine("Username:"******"Password:"******"http://localhost:3915/Account/Login"; var client = new HttpClient(); var response = client.PostAsync(uri, new User() { Username = username, Password = password }, new JsonMediaTypeFormatter()).Result; IEnumerable<string> values; response.Headers.TryGetValues("Set-Cookie", out values); if (null == values || string.IsNullOrEmpty(values.First())) { Console.WriteLine("Invalid Username or password;"); } else { string newUri = "http://localhost:3915/customer/get/1"; string cookie = values.First(); client.DefaultRequestHeaders.Add("Cookie", cookie); var getRequestResponse = client.GetAsync(newUri).Result; Customer customer = getRequestResponse.Content.ReadAsAsync<Customer>().Result; Console.WriteLine("Customer Id: {0}; Name: {1}", customer.Id, customer.Name); } Console.ReadLine(); }
public ActionResult AddFinance(SearchFinanceModel model) { Session["Finance"] = null; IEnumerable<FinanceModel> objBE; using (var client = new HttpClient()) { model.addFinance.insertUserId = base.CurrentUserID; client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["APIURI"]); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PutAsJsonAsync("finance/SaveFinanceActivity", model.addFinance).Result; if (response.IsSuccessStatusCode) { string jsonResult = response.Content.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(jsonResult) && !jsonResult.Equals("[]")) { objBE = JsonConvert.DeserializeObject<IEnumerable<FinanceModel>>(jsonResult); model.addFinance.finance = objBE; } else model.addFinance.finance = null; } model.activityType = (IEnumerable<SelectListItem>)Session["ActivityType"]; model.processorCompany = (IEnumerable<SelectListItem>)Session["Processor"]; model.addFinance.activityType = (IEnumerable<SelectListItem>)Session["ActivityType"]; model.addFinance.processorCompany = (IEnumerable<SelectListItem>)Session["Processor"]; ViewBag.SuccessMsg = Pecuniaus.Resources.Finance.Finance.FinanceAddedSuccessfully; } return View("Index", model); }
public override async Task<List<TimelineData>> GetTimelineAsync() { var token = await GetAccessTokenAsync(); var client = new HttpClient { MaxResponseContentBufferSize = 1024 * 1024 }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = await client.GetAsync(string.Format("{0}?screen_name={1}", StatusesUserTimeline, WebUtility.UrlEncode(ScreenName))); var json = JsonValue.Parse(await response.Content.ReadAsStringAsync()); var statuses = json.GetArray(); return statuses.Select(status => status.GetObject()) .Select(status => { var text = status.GetNamedString("text"); var user = status.GetNamedObject("user"); var created = status.GetNamedString("created_at"); var name = user.GetNamedString("name"); var screenname = user.GetNamedString("screen_name"); var profileImageUrl = user.GetNamedString("profile_image_url_https"); return new TweetData { Title = string.Format("{0} / @{1}", name, screenname), Body = text, ImageUri = new Uri(profileImageUrl), Name = name, ScreenName = screenname, CreatedAt = ParseCreatedString(created) }; }) .Cast<TimelineData>() .ToList(); }
/// <summary> /// </summary> /// <param name="name"></param> /// <param name="region"></param> /// <returns>The last 10 games the summoner has played.</returns> public async Task<List<GameDTO>> GetSummonersRecentGamesAsync(Summoner summoner) { if (summoner == null) { throw new ArgumentNullException("summoner"); } if (summoner.ID == 0) { throw new ArgumentException("Summoner ID should be a value larger than 0."); } string requestPath = string.Format("game/by-summoner/{0}/recent", summoner.ID); string url = BuildURL(summoner.Region, requestPath); using (HttpClient client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(url)) using (HttpContent content = response.Content) { string contentStr = await content.ReadAsStringAsync(); GameHistoryDTO gameHistoryDTO = await JsonConvert.DeserializeObjectAsync<GameHistoryDTO>(contentStr); if (gameHistoryDTO == null) { return null; } return gameHistoryDTO.games; } }
public IActionResult OAuth(string code) { if (string.IsNullOrEmpty(code)) { throw new ArgumentException("Invalid parameters"); } using (var client = new HttpClient()) { var getTokenUri = this.BuildGetTokenUri(OAuthInfo.ClientId, OAuthInfo.SecretId, OAuthInfo.RedirectedUri, code); var response = client.GetAsync(getTokenUri); if (response.Result.IsSuccessStatusCode) { string result = response.Result.Content.ReadAsStringAsync().Result; var resultObjectTemplate = new { ok = false, access_token = string.Empty, error = string.Empty }; var resultObject = JsonConvert.DeserializeAnonymousType(result, resultObjectTemplate); if (resultObject.ok) { this.ViewData["Message"] = $"You Slack token is: {resultObject.access_token}"; } else { this.ViewData["Message"] = $"Unable to retrieve Slack token. Error: {resultObject.error}"; } } else { throw new Exception(response.Result.ReasonPhrase); } } return this.View(); }
public async Task InvokeRequestResponseService(object scoreRequest, string baseUrl, string key) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key); client.BaseAddress = new Uri(baseUrl); HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); Console.WriteLine("Result: {0}", result); } else { Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode)); // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure Console.WriteLine(response.Headers.ToString()); string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } } }
private async Task TryPostJsonAsync() { try { // Construct the HttpClient and Uri. This endpoint is for test purposes only. //var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); //myFilter.AllowUI = false; //Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); //Windows.Storage.StorageFolder storageFolder = KnownFolders.DocumentsLibrary; fileOpenPicker.FileTypeFilter.Add(".json"); /*fileOpenPicker.FileTypeFilter.Add(".txt"); * Windows.Storage.StorageFile credentialsFile = await fileOpenPicker.PickSingleFileAsync(); * string text = await Windows.Storage.FileIO.ReadTextAsync(credentialsFile); * string username = text.Split(',')[0]; * string password = text.Split(',')[1]; * string domain = text.Split(',')[2];*/ HttpClientHandler handler = new HttpClientHandler(); handler.Credentials = new NetworkCredential("", "", ""); System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(handler); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); Uri uri = new Uri("https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json"); // Construct the JSON to post. //fileOpenPicker.FileTypeChoices.Add("JSON", new List<string>() { ".json" }); IStorageFile jsonFile = await fileOpenPicker.PickSingleFileAsync(); IRandomAccessStream stream = await jsonFile.OpenAsync(FileAccessMode.Read); System.Net.Http.MultipartFormDataContent postContent = new MultipartFormDataContent(); if (stream != null) { using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)stream.Size); string jsonText = dataReader.ReadString(numBytesLoaded); System.Net.Http.StringContent streamContent = new System.Net.Http.StringContent(jsonText); streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); postContent.Add(streamContent); System.Net.Http.HttpResponseMessage httpResponseMessage = await httpClient.PostAsync( "https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json", postContent); // Make sure the post succeeded, and write out the response. httpResponseMessage.EnsureSuccessStatusCode(); var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync(); Debug.WriteLine(httpResponseBody); } } else { Debug.WriteLine("stream is NULL."); } //HttpStringContent content = await jsonFile.OpenReadAsync(); // Post the JSON and wait for a response. } catch (Exception ex) { // Write out any exceptions. Debug.WriteLine(ex); } }
public StandardHttpClient(IHttpContextAccessor httpContextAccessor) { _client = new System.Net.Http.HttpClient(); _httpContextAccessor = httpContextAccessor; }
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder) { base.PrepareRequest(client, request, urlBuilder); }
public static async Task <ResponseEnvelope> PerformThrottledRemoteProcedureCall <TRequest>(this System.Net.Http.HttpClient client, string url, RequestEnvelope requestEnvelope) where TRequest : IMessage <TRequest> { rpcQueue.Enqueue(requestEnvelope); var count = rpcQueue.Count; mutex.WaitOne(); RequestEnvelope r; while (rpcQueue.TryDequeue(out r)) { var diff = Math.Max(0, DateTime.Now.Millisecond - lastRpc); if (diff < minDiff) { var delay = (minDiff - diff) + (int)(new Random().NextDouble() * 0); // Add some randomness await Task.Delay((int)(delay)); } lastRpc = DateTime.Now.Millisecond; ResponseEnvelope response = await PerformRemoteProcedureCall <TRequest>(client, url, requestEnvelope); responses.GetOrAdd(r, response); } ResponseEnvelope ret; responses.TryRemove(requestEnvelope, out ret); mutex.Release(); return(ret); }
private static async Task <ResponseEnvelope> PerformRemoteProcedureCall <TRequest>(this System.Net.Http.HttpClient client, string url, RequestEnvelope requestEnvelope) where TRequest : IMessage <TRequest> { Logger.Error("URL: " + url); //Encode payload and put in envelop, then send var data = requestEnvelope.ToByteString(); var result = await client.PostAsync(url, new ByteArrayContent(data.ToByteArray())); //Decode message var responseData = await result.Content.ReadAsByteArrayAsync(); var codedStream = new CodedInputStream(responseData); var decodedResponse = new ResponseEnvelope(); decodedResponse.MergeFrom(codedStream); return(decodedResponse); }
private static async Task <ResponseEnvelope> PerformRemoteProcedureCall <TRequest>(this System.Net.Http.HttpClient client, Client apiClient, RequestEnvelope requestEnvelope) where TRequest : IMessage <TRequest> { // Check killswitch from url before making API calls. if (!apiClient.Settings.UseLegacyAPI) { if (apiClient.CheckCurrentVersionOutdated()) { throw new MinimumClientVersionException(apiClient.CurrentApiEmulationVersion, apiClient.MinimumClientVersion); } } //Encode payload and put in envelop, then send var data = requestEnvelope.ToByteString(); var result = await client.PostAsync(apiClient.ApiUrl, new ByteArrayContent(data.ToByteArray())).ConfigureAwait(false); //Decode message var responseData = await result.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var codedStream = new CodedInputStream(responseData); ResponseEnvelope serverResponse = new ResponseEnvelope(); serverResponse.MergeFrom(codedStream); // Process Platform8Response CommonRequest.ProcessPlatform8Response(apiClient, serverResponse); if (!string.IsNullOrEmpty(serverResponse.ApiUrl)) { apiClient.ApiUrl = "https://" + serverResponse.ApiUrl + "/rpc"; } if (serverResponse.AuthTicket != null) { if (serverResponse.AuthTicket.ExpireTimestampMs > (ulong)Utils.GetTime(true)) { apiClient.AuthTicket = serverResponse.AuthTicket; } else { // Expired auth ticket. apiClient.AuthTicket = null; } } switch (serverResponse.StatusCode) { case ResponseEnvelope.Types.StatusCode.InvalidAuthToken: await apiClient.RequestBuilder.RegenerateRequestEnvelopeWithNewAccessToken(requestEnvelope).ConfigureAwait(false); return(await PerformRemoteProcedureCall <TRequest>(client, apiClient, requestEnvelope).ConfigureAwait(false)); case ResponseEnvelope.Types.StatusCode.Redirect: // 53 means that the api_endpoint was not correctly set, should be at this point, though, so redo the request return(await PerformRemoteProcedureCall <TRequest>(client, apiClient, requestEnvelope).ConfigureAwait(false)); case ResponseEnvelope.Types.StatusCode.BadRequest: // Your account may be banned! please try from the official client. throw new APIBadRequestException("BAD REQUEST \r\n" + JsonConvert.SerializeObject(requestEnvelope)); case ResponseEnvelope.Types.StatusCode.Unknown: break; case ResponseEnvelope.Types.StatusCode.Ok: break; case ResponseEnvelope.Types.StatusCode.OkRpcUrlInResponse: break; case ResponseEnvelope.Types.StatusCode.InvalidRequest: break; case ResponseEnvelope.Types.StatusCode.InvalidPlatformRequest: break; case ResponseEnvelope.Types.StatusCode.SessionInvalidated: throw new SessionInvalidatedException("SESSION INVALIDATED EXCEPTION"); default: throw new ArgumentOutOfRangeException(); } return(serverResponse); }
//#if !NET35 && !NET40 /// <summary> /// 从Url下载,并保存到指定目录 /// </summary> /// <param name="serviceProvider">.NetCore 下的服务器提供程序,如果 .NET Framework 则保留 null</param> /// <param name="url">需要下载文件的Url</param> /// <param name="filePathName">保存文件的路径,如果下载文件包含文件名,按照文件名储存,否则将分配Ticks随机文件名</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static string Download(IServiceProvider serviceProvider, string url, string filePathName, int timeOut = 999) { var dir = Path.GetDirectoryName(filePathName) ?? "/"; Directory.CreateDirectory(dir); #if NET45 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = timeOut; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { string responseFileName = null; var contentDescriptionHeader = response.GetResponseHeader("Content-Disposition"); if (!string.IsNullOrEmpty(contentDescriptionHeader)) { var fileName = Regex.Match(contentDescriptionHeader, @"(?<=filename="")([\s\S]+)(?= "")", RegexOptions.IgnoreCase).Value; responseFileName = Path.Combine(dir, fileName); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(filePathName, FileMode.OpenOrCreate)) { byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { fs.Write(bArr, 0, size); fs.Flush(); size = responseStream.Read(bArr, 0, (int)bArr.Length); } } return(fullName); } #else System.Net.Http.HttpClient httpClient = serviceProvider.GetRequiredService <SenparcHttpClient>().Client; using (var responseMessage = httpClient.GetAsync(url).Result) { if (responseMessage.StatusCode == HttpStatusCode.OK) { string responseFileName = null; //ContentDisposition可能会为Null if (responseMessage.Content.Headers.ContentDisposition != null && responseMessage.Content.Headers.ContentDisposition.FileName != null && responseMessage.Content.Headers.ContentDisposition.FileName != "\"\"") { responseFileName = Path.Combine(dir, responseMessage.Content.Headers.ContentDisposition.FileName.Trim('"')); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(fullName, FileMode.Create)) { using (var responseStream = responseMessage.Content.ReadAsStreamAsync().Result) { responseStream.CopyTo(fs); fs.Flush(); } } return(fullName); } else { return(null); } } #endif }
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url) { base.PrepareRequest(client, request, url); }
private bool join(string comId, CookieContainer cc, MainForm form, config.config cfg, bool isPlayOnlyMode) { for (int i = 0; i < 5; i++) { //var myPageUrl = "https://www.nicovideo.jp/my"; var comUrl = "https://com.nicovideo.jp/community/" + comId; var url = "https://com.nicovideo.jp/motion/" + comId; var headers = new WebHeaderCollection(); headers.Add("Upgrade-Insecure-Requests", "1"); headers.Add("User-Agent", util.userAgent); try { var cg = new CookieGetter(cfg); var cgret = cg.getHtml5RecordCookie(url); cgret.Wait(); // cgret.ConfigureAwait(false); if (cgret == null || cgret.Result == null) { System.Threading.Thread.Sleep(3000); continue; } var _cc = cgret.Result[0]; // var _cc = cgret.Result[(isSub) ? 1 : 0]; // util.debugWriteLine(cg.pageSource); var res = util.getPageSource(url, _cc, comUrl); var isJidouShounin = res.IndexOf("自動承認されます") > -1; // var _compage = util.getPageSource(url, ref headers, cc); // var gateurl = "http://live.nicovideo.jp/gate/lv313793991"; // var __gatePage = util.getPageSource(gateurl, ref headers, cc); // var _compage2 = util.getPageSource(url, ref headers, cc); // util.debugWriteLine(cc.GetCookieHeader(new Uri(url))); var msg = (isJidouShounin ? "フォローを試みます。" : "自動承認ではありませんでした。"); form.addLogText(msg); if (!isJidouShounin) { return(false); } } catch (Exception e) { util.debugWriteLine(e.Message + e.Source + e.StackTrace + e.TargetSite); return(false); } try { var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = cc; handler.Proxy = util.httpProxy; var http = new System.Net.Http.HttpClient(handler); http.DefaultRequestHeaders.Referrer = new Uri(url); var content = new System.Net.Http.FormUrlEncodedContent(new Dictionary <string, string> { { "mode", "commit" }, { "title", "フォローリクエスト" } }); var enc = Encoding.GetEncoding("UTF-8"); string data = "mode=commit&title=" + System.Web.HttpUtility.UrlEncode("フォローリクエスト", enc); byte[] postDataBytes = Encoding.ASCII.GetBytes(data); var req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Proxy = util.httpProxy; req.CookieContainer = cc; req.Referer = url; req.ContentLength = postDataBytes.Length; req.ContentType = "application/x-www-form-urlencoded"; req.Headers.Add("Accept-Encoding", "gzip,deflate"); req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // req.Headers.Add("Referer", url); using (var stream = req.GetRequestStream()) { try { stream.Write(postDataBytes, 0, postDataBytes.Length); } catch (Exception e) { util.debugWriteLine(e.Message + " " + e.StackTrace + " " + e.Source + " " + e.TargetSite); } } // stream.Close(); var res = req.GetResponse(); using (var resStream = new System.IO.StreamReader(res.GetResponseStream())) { var resStr = resStream.ReadToEnd(); var isSuccess = resStr.IndexOf("フォローしました") > -1; var _m = (isPlayOnlyMode) ? "視聴" : "録画"; form.addLogText((isSuccess ? "フォローしました。" + _m + "開始までしばらくお待ちください。" : "フォローに失敗しました。")); return(isSuccess); } // resStream.Close(); // Task<HttpResponseMessage> _resTask = http.PostAsync(url, content); // _resTask.Wait(); // var _res = _resTask.Result; // var resTask = _res.Content.ReadAsStringAsync(); // resTask.Wait(); // var res = resTask.Result; // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; // var cc = handler.CookieContainer; } catch (Exception e) { form.addLogText("フォローに失敗しました。"); util.debugWriteLine(e.Message + e.StackTrace); continue; // return false; } } form.addLogText("フォローに失敗しました。"); util.debugWriteLine("フォロー失敗"); return(false); }
static void Main(string[] args) { var client = new System.Net.Http.HttpClient(); string response = string.Empty; string authHeader = string.Empty; string verb = string.Empty; string resourceType = string.Empty; string resourceId = string.Empty; string resourceLink = string.Empty; client.DefaultRequestHeaders.Add("x-ms-date", utc_date); client.DefaultRequestHeaders.Add("x-ms-version", "2017-07-29"); //LIST all databases verb = "GET"; resourceType = "dbs"; resourceId = string.Empty; resourceLink = string.Format("dbs"); authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0"); client.DefaultRequestHeaders.Remove("Authorization"); client.DefaultRequestHeaders.Add("Authorization", authHeader); client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("ContentType", "application/json"); response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result; //GET a database verb = "GET"; resourceType = "dbs"; resourceLink = "dbs/" + databaseId; resourceId = (idBased) ? resourceLink : databaseId.ToLowerInvariant(); authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0"); client.DefaultRequestHeaders.Remove("authorization"); client.DefaultRequestHeaders.Add("authorization", authHeader); response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result; //LIST all collections verb = "GET"; resourceType = "colls"; resourceLink = string.Format("dbs/{0}/colls", databaseId); resourceId = (idBased) ? string.Format("dbs/{0}", databaseId) : databaseId.ToLowerInvariant(); authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0"); client.DefaultRequestHeaders.Remove("authorization"); client.DefaultRequestHeaders.Add("authorization", authHeader); response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result; //GET a collections verb = "GET"; resourceType = "colls"; resourceLink = string.Format("dbs/{0}/colls/{1}", databaseId, collectionId); resourceId = (idBased) ? resourceLink : collectionId.ToLowerInvariant(); authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0"); client.DefaultRequestHeaders.Remove("authorization"); client.DefaultRequestHeaders.Add("authorization", authHeader); response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result; //LIST all documents in a collection verb = "GET"; resourceType = "docs"; resourceLink = string.Format("dbs/{0}/colls/{1}/docs", databaseId, collectionId); resourceId = (idBased) ? string.Format("dbs/{0}/colls/{1}", databaseId, collectionId) : collectionId.ToLowerInvariant(); authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0"); client.DefaultRequestHeaders.Remove("authorization"); client.DefaultRequestHeaders.Add("authorization", authHeader); response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result; //GET a document verb = "GET"; resourceType = "docs"; resourceLink = string.Format("dbs/{0}/colls/{1}/docs/{2}", databaseId, collectionId, documentId); resourceId = (idBased) ? resourceLink : documentId.ToLowerInvariant(); authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0"); client.DefaultRequestHeaders.Remove("authorization"); client.DefaultRequestHeaders.Add("authorization", authHeader); response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result; //EXECUTE a query verb = "POST"; resourceType = "docs"; resourceLink = string.Format("dbs/{0}/colls/{1}/docs", databaseId, collectionId); resourceId = (idBased) ? string.Format("dbs/{0}/colls/{1}", databaseId, collectionId) : collectionId.ToLowerInvariant(); authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0"); client.DefaultRequestHeaders.Remove("authorization"); client.DefaultRequestHeaders.Add("authorization", authHeader); client.DefaultRequestHeaders.Add("x-ms-documentdb-isquery", "True"); var qry = new SqlQuerySpec { query = "SELECT * FROM root" }; var r = client.PostWithNoCharSetAsync(new Uri(baseUri, resourceLink), qry).Result; Console.WriteLine(r.Content.ToString()); }
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response);
/// <summary> /// Get System.Net.Http.HttpClient instance /// </summary> /// <returns>System.Net.Http.HttpClient instance</returns> protected System.Net.Http.HttpClient GetHttpClient() { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); return(httpClient); }
/// <summary>Add new entries.</summary> /// <param name="body">Entries to be uploaded.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Rejected list of entries. Empty list is success.</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task AddDeviceStatusAsync(System.Collections.Generic.IEnumerable <DeviceStatus> body, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append("/devicestatus"); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body)); // content_.Headers.ContentType.MediaType = "application/json"; content_.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); request_.Content = content_; request_.Method = HttpMethod.Post;// new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "405") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("Invalid input", status_, responseData_, headers_, null); } else if (status_ == "200") { return; } else if (status_ != "200" && status_ != "204") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
private async void btnAddDirecc_Clicked(object sender, EventArgs e) { var descx = desc.Text; var gpx = gp.Text; if (String.IsNullOrEmpty(gp.Text)) { gpx = "Referencia no encontrada"; } if (string.IsNullOrEmpty(descx)) { await DisplayAlert("Descripcion", "Ingrese una descripcion", "ok"); desc.Focus(); } else if (string.IsNullOrEmpty(Latitud.Text)) { await DisplayAlert("Error", "Ha habido un error con el GPS verifique que este cuente con este servicio activado", "ok"); } else if (string.IsNullOrEmpty(Longitud.Text)) { await DisplayAlert("Error", "Ha habido un error con el GPS verifique que este cuente con este servicio activado", "ok"); } else { try { userDataBase = new UserDataBase(); var user_exist = userDataBase.GetMembers().ToList(); var httpClient = new System.Net.Http.HttpClient(); var value_check = new Dictionary <string, string> { { "descripcion", descx }, { "id_usuario", user_exist[0].id_cliente.ToString() }, { "direccion", gpx }, // {"direccion", descx }, { "latitude", Latitud.Text }, { "longitude", Longitud.Text }, }; var content = new FormUrlEncodedContent(value_check); //solicitud/agrega HttpClient client = new HttpClient(); // IsSuccessStatusCode = false var responseMsg = await httpClient.PostAsync("http://www.washdryapp.com/app/public/direccion/guardar", content); // ... subir a internet if (responseMsg.IsSuccessStatusCode) { string xjson = await responseMsg.Content.ReadAsStringAsync(); await DisplayAlert("Exito", "Direccion agregada correctamente. ", "ok"); GetVisitasWeb(); //await DisplayAlert("error", "error status 419 Probelmas con respuesta del server, intente mas tarde o reinicie la aplicacion", "ok"); } else { string xjson = await responseMsg.Content.ReadAsStringAsync(); switch (responseMsg.StatusCode) { case System.Net.HttpStatusCode.BadRequest: await DisplayAlert("error", "error status 400 Unauthorized", "ok"); break; case System.Net.HttpStatusCode.Forbidden: await DisplayAlert("error", "error status 403 ", "ok"); break; case System.Net.HttpStatusCode.NotFound: await DisplayAlert("200", "error status 404 ", "ok"); break; case System.Net.HttpStatusCode.RequestEntityTooLarge: await DisplayAlert("error", "error status 413 ", "ok"); break; case System.Net.HttpStatusCode.RequestTimeout: await DisplayAlert("error", "error status 408 ", "ok"); break; case System.Net.HttpStatusCode.Unauthorized: await DisplayAlert("error", "yeah status 401 Unauthorized", "ok"); break; } } } catch (Exception ex) { await DisplayAlert("error", "Error : " + ex.ToString(), "ok"); } } }
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); }
/// <summary> /// Create new HttpClient /// </summary> /// <param name="httpClient">HTTP client to use</param> public SystemNetHttpClient(System.Net.Http.HttpClient httpClient = null) { _httpClient = httpClient ?? new System.Net.Http.HttpClient(); }
//private string issueKey; public void NewFeatureCheckCreate(string featureName, string featureFilePath) { List <string> results = new List <string>(); //string issuenum = null; string fileName = featureFilePath; string tktID = null; string tkyKey = null; string JiraUserName = ConfigurationManager.AppSettings["username"].ToString(); string JiraPassword = ConfigurationManager.AppSettings["password"].ToString(); string systemUsr = Environment.UserName; string ProjFolderPath = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString(); //Checking whether the new feature already exists, if true, do not create a new ticket HttpClient client1 = new HttpClient(); string Apiurl = ("https://spiderlogic.jira.com/rest/api/2/search?jql=project=SFLOW&fields=description&fields=summary"); var credentials = Encoding.ASCII.GetBytes(JiraUserName + ":" + JiraPassword); client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials)); Uri uri = new Uri(Apiurl.ToString()); string ApiResponse = client1.GetStringAsync(uri).Result; var root = JsonConvert.DeserializeObject <RootObject>(ApiResponse); var Sumry = root.issues.Count; //Checking if the new feature already exists by iterating though the issue list in jira bool FeatureExists = false; var issues = root.issues; string[] textLinesFT = System.IO.File.ReadAllLines(fileName); //Finding the feature name from the feature file which will be the name of the ticket string FeatureKeyword = "Feature"; string FeaureTRName = string.Empty; foreach (string line2 in textLinesFT) { if (line2.Contains(FeatureKeyword)) { results.Add(line2); FeaureTRName = line2; } } //Trim the New Feature name to display only the Feature name FeaureTRName = FeaureTRName.Replace("Feature: ", ""); foreach (var item in issues) { var fields = item.fields; var summary = (fields.summary).ToString(); if (summary.Equals(FeaureTRName)) { Console.WriteLine("New Feature already exists in the project"); FeatureExists = true; tktID = item.id; tkyKey = item.key; } } //Check if the scenario already exists in JIRA within the Feature bool ScenarioExists = false; //If the new feature does not exist, create a new feature by using the POST method in JIRA via API if (FeatureExists == false) { string text = System.IO.File.ReadAllText(fileName); string searchKeyword = "Feature"; string[] textLines = System.IO.File.ReadAllLines(fileName); string FTRName = string.Empty; foreach (string line in textLines) { if (line.Contains(searchKeyword)) { results.Add(line); FTRName = line; } } string DescText; int pFrom = text.IndexOf("@") + "@".Length; string reslt = text.Substring(pFrom); DescText = "@" + reslt; string SnrKeyword = "Scenario Outline:"; string ScrName = string.Empty; foreach (string line in textLines) { if (line.Contains(SnrKeyword)) { results.Add(line); ScrName = line; } } //Trim the new feature name to display only the Feature name FTRName = FTRName.Replace("Feature: ", ""); //The fields required to create a new JIRA ticket var data = new Issue(); data.fields.project.key = "SFLOW"; data.fields.summary = FTRName; // data.fields.description = reslt; //data.fields.description = text; data.fields.description = DescText; // data.fields.issuetype.name = "User Story"; data.fields.issuetype.name = "New Feature"; string postUrl = "https://spiderlogic.jira.com/rest/api/latest/"; System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new System.Uri(postUrl); byte[] cred = UTF8Encoding.UTF8.GetBytes(JiraUserName + ":" + JiraPassword); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred)); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent <Issue>(data, jsonFormatter); System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; Console.Write(result); } else { Console.Write(response.StatusCode.ToString()); } } else { //This section is to update the jira ticket if a new scenario is added in the feature file if (FeatureExists == true && ScenarioExists == false) { Console.Out.WriteLine("New scenario found and hence updating the ticket with the new scenario"); ////string descriptNew = System.IO.File.ReadAllText(@"C:\Users\subrahp\Documents\Visual Studio 2015\Projects\FlipkartExcelSpecRunCartTest\FlipkartExcelSpecRunCartTest\FlipkartExcelSpecrunCartTest.feature"); //string descriptNew = System.IO.File.ReadAllText(fileName); //string descriptNew2 = descriptNew.Replace(';', ' ').Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ').Replace("\n\n", " "); ////Get the id from the existing new feature to update the description and post with the updated description //var PostURL2 = "?jql=project=SFLOW&fields=description&fields=summary"; //var POSTRequest = "https://spiderlogic.jira.com/rest/api/2/issue/"; //var request = WebRequest.Create(POSTRequest + tkyKey + PostURL2); //request.Method = "PUT"; //request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(JiraUserName + ":" + JiraPassword))); //request.ContentType = "application/json"; //var json = string.Format("{{ \"update\": {{\"description\": [{{\"set\":\"{0}\"}}] }} }};", descriptNew2); //request.GetRequestStream().Write(Encoding.ASCII.GetBytes(json), 0, json.Length); //var response = request.GetResponse(); //var reader = new StreamReader(response.GetResponseStream()); //var output = reader.ReadToEnd(); } } }
public AssetAdministrationShellRepositoryHttpClient(System.Net.Http.HttpClient httpClient) : base(httpClient) { }
public HttpClient(string uri) { client = new System.Net.Http.HttpClient(); baseUri = uri; }
public ProductHttpClient(System.Net.Http.HttpClient client) { client.BaseAddress = new Uri("https://product.eshp.com/api/"); Client = client; }
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url) { string key = this.ApiKey.Sha1Digest(); request.Headers.Add("API-SECRET", key); }
public HttpRequestFactory(System.Net.Http.HttpClient httpClient) { _httpClient = httpClient; }
private async void CameraOption(object sender, EventArgs e) { try { if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { await DisplayAlert("No Camera", ":( No camera avaialble.", "OK"); return; } var mediaOptions = new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "ShopRConnect", Name = $"{DateTime.UtcNow}.jpg" }; file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { CompressionQuality = 20, PhotoSize = PhotoSize.Small }); p = file.Path; FilePathPre = "awsimage" + p; FileName = file.Path; FileName = FileName.Substring(FileName.LastIndexOf("/") + 1); FileNamePre = "awsimage" + FileName; var content = new MultipartFormDataContent(); Actimageupload.IsRunning = true; await Task.Delay(TimeSpan.FromSeconds(0.01)); content.Add(new StreamContent(file.GetStream()), "\"file\"", $"\"{file.Path}\""); var httpClient = new System.Net.Http.HttpClient(); // var uploadServiceBaseAddress = "http://maudit.elixirct.net/Uploadfiletoserver/api/Files/Upload"; var uploadServiceBaseAddress = "http://elixirct.in/ShopRConservicePublish/api/Files/Upload"; var httpResponseMessage = await httpClient.PostAsync(uploadServiceBaseAddress, content); if (httpResponseMessage.ReasonPhrase.Equals("OK")) { MessagingCenter.Send <View.Popup_ImageDialog, string>(this, "awsimagename", FilePathPre); string url = "http://elixirct.in/ShopRConservicePublish/Uploads/" + FileName; await Task.Delay(TimeSpan.FromSeconds(0.01)); DependencyService.Get <IFileService>().DownloadFile(url, getGalleryPath()); // download.DownloadFile(url, "ShopRConnect"); // MessagingCenter.Send<View.Popup_ImageDialog, string>(this, "awsimagename", FileNamePre); await Navigation.PopPopupAsync(); Actimageupload.IsRunning = false; } else { await DisplayAlert("Alert", "Network Issue", "OK"); Actimageupload.IsRunning = false; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); // await DisplayAlert("Alert", "Please check your Internet connection", "Ok"); Actimageupload.IsRunning = false; // await Navigation.PopPopupAsync(); } }
public async Task HttpSample(HttpMessageHandler handler) { var client = new System.Net.Http.HttpClient(handler); ad.RenderStream(await client.GetStreamAsync(Application.WisdomUrl)); }
public async Task HttpSample() { var client = new System.Net.Http.HttpClient(new CFNetworkHandler()); ad.RenderRssStream(await client.GetStreamAsync(Application.WisdomUrl)); }
public static int Main(string[] args) { if (args.Length != 0) { if (args[0].ToLower() == "send" && args.Count() == 3) { string computerName = args[1]; string message = args[2]; string urlOfServer; try { using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) { using (RegistryKey centralNetSendKey = hklm.OpenSubKey(@"SOFTWARE\Tulpep\CentralNetSend")) { urlOfServer = centralNetSendKey.GetValue("APIServer").ToString(); } } } catch { Console.WriteLine(@"Check that HKEY_LOCAL_MACHINE\SOFTWARE\Tulpep\CentralNetSend\APIServer exists"); return(1); } try { var httpclient = new System.Net.Http.HttpClient(new HttpClientHandler { UseDefaultCredentials = true, UseProxy = false }) { BaseAddress = new Uri(urlOfServer) }; var response = httpclient.PostAsJsonAsync("/api/Message?computerName=" + computerName + "&message=" + message, "").Result; if (response.StatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("Failed. " + response.Content.ReadAsStringAsync().Result); } } catch { Console.WriteLine("Cannot contact Central Net Service by Tulpep at " + urlOfServer); return(1); } } else { var process = new Process(); process.StartInfo.FileName = "netoriginal.exe"; process.StartInfo.Arguments = String.Join(" ", args); // set up output redirection process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.EnableRaisingEvents = true; // see below for output handler process.ErrorDataReceived += ShowInfoOfNet; process.OutputDataReceived += ShowInfoOfNet; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); } } return(0); }
public HttpClientHelper(System.Net.Http.HttpClient httpClient) { httpClient.BaseAddress = new Uri("https://waimaiopen.meituan.com/api/v1/"); Client = httpClient; }
//get bulk products details through webapi public async Task <ActionResult> UploadExternalAPI(HttpPostedFileBase file) { DataTable _upcCSVCode = new DataTable(); string path = string.Empty; var fileName = string.Empty; var UPCCode = string.Empty; int _yes = 1; bool _isFirstRowHeader = Convert.ToBoolean(_yes); string _retrunProductDetail = string.Empty; ArrayList _upcCodeListForCSV = new ArrayList(); List <dynamic> _list = new List <dynamic>(); StringBuilder sb = new StringBuilder(); DataTable dt = new DataTable(); DataSet _productDataset = new DataSet(); if (file.ContentLength > 0) { fileName = Path.GetFileName(file.FileName); path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); file.SaveAs(path); _upcCSVCode = GetDataTableFromCsv(path, _isFirstRowHeader); if (_upcCSVCode.Rows.Count > 0) { for (int i = 0; i < _upcCSVCode.Rows.Count; i++) { UPCCode = _upcCSVCode.Rows[i][0].ToString(); if (UPCCode != null) { string _appKey = "/zDQJTHnn1dS"; string _authKey = "Yj83A3i3i5Kc8Wi6"; string _signature = GetDigitEyesVerificationCode(UPCCode, _authKey);//Third party eye method to get sample signature of particuler upc code string _url = "https://www.digit-eyes.com/gtin/v2_0/?upcCode=" + UPCCode + "&field_names=all&language=en&app_key=" + _appKey + "&signature=" + _signature + ""; string[] _jsonProductArray; using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { client.BaseAddress = new Uri(_url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); System.Net.Http.HttpResponseMessage response = await client.GetAsync(_url); if (response.IsSuccessStatusCode) { _retrunProductDetail = await response.Content.ReadAsStringAsync(); _jsonProductArray = Regex.Split(_retrunProductDetail.Replace(", gcp", ""), "},{"); string[] jsonStringArray = Regex.Split(_retrunProductDetail.Replace("[", "").Replace("]", "").Replace(", Inc.", " Inc."), "},{"); if (dt.Columns.Count <= 0) { List <string> ColumnsName = new List <string>(); foreach (string jSA in jsonStringArray) { string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ","); foreach (string ColumnsNameData in jsonStringData) { try { int idx = ColumnsNameData.IndexOf(":"); string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", ""); if (!ColumnsName.Contains(ColumnsNameString)) { ColumnsName.Add(ColumnsNameString); } } catch (Exception ex) { throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData)); } } break; } foreach (string AddColumnName in ColumnsName) { var _columnName = Regex.Replace(AddColumnName, @"\s+", ""); if (dt.Columns.Contains(_columnName)) { dt.Columns.Add("gcp1"); } else { dt.Columns.Add(_columnName); } } dt.Rows.Add(JsonStringToDataTable(jsonStringArray, dt)); } else { dt.Rows.Add(JsonStringToDataTable(jsonStringArray, dt)); } } } } } string _convertProductetailsToCSV = ConvertToCSV(dt);//convert to csv file _saveProductsDetailCSVFile(_convertProductetailsToCSV.ToString()); string _retrunProductsDetail = JsonConvert.SerializeObject(_productDataset, Formatting.Indented); TempData["ProductDetailList"] = _retrunProductsDetail; return(RedirectToAction("UPCSearch")); } else { TempData["sErrMsg"] = "Please Add UPC Code in .csv file !"; } } else { return(RedirectToAction("UPCSearch")); } return(RedirectToAction("UPCSearch")); }
public static async Task <ResponseEnvelope> PerformThrottledRemoteProcedureCall <TRequest>(this System.Net.Http.HttpClient client, string url, RequestEnvelope requestEnvelope) where TRequest : IMessage <TRequest> { rpcQueue.Enqueue(requestEnvelope); var count = rpcQueue.Count; mutex.WaitOne(); RequestEnvelope r; while (rpcQueue.TryDequeue(out r)) { var diff = Math.Max(0, (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds - lastRpc); if (diff < minDiff) { var delay = (int)((minDiff - diff) + (int)(new Random().NextDouble() * 0)); // Add some randomness RandomHelper.RandomSleep(delay, delay + 100); } lastRpc = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds; ResponseEnvelope response = await PerformRemoteProcedureCall <TRequest>(client, url, r).ConfigureAwait(false); responses.GetOrAdd(r, response); } ResponseEnvelope ret; responses.TryRemove(requestEnvelope, out ret); mutex.Release(); return(ret); }
private async static Task <CitrixAuthCredential> GetCredentialsFromStoreFront(string SFURL, string Username, string Password, string Domain, bool IsSSL) { CitrixAuthCredential _sfCredential = null; Dictionary <string, string> _returnedValues = new Dictionary <string, string>(); string _csrfToken = Guid.NewGuid().ToString(); string _aspnetSessionID = Guid.NewGuid().ToString(); string _username = Username; string _password = Password; string _domain = Domain; string _authenticationBody = string.Format(@"username={0}\{1}&password={2}", _domain, _username, _password); CookieContainer _cookieContainer = new CookieContainer(); HttpClientHandler _clientHandler = new HttpClientHandler(); _clientHandler.CookieContainer = _cookieContainer; System.Net.Http.HttpClient _client = new System.Net.Http.HttpClient(_clientHandler); //_client.BaseAddress = new Uri(SFURL); string _postAuthUrl = (SFURL.EndsWith("/")) ? "PostCredentialsAuth/Login" : "/PostCredentialsAuth/Login"; string _postURL = string.Format("{0}{1}", SFURL, _postAuthUrl); if (IsSSL) { _client.DefaultRequestHeaders.Add("X-Citrix-IsUsingHTTPS", "Yes"); } else { _client.DefaultRequestHeaders.Add("X-Citrix-IsUsingHTTPS", "No"); } _client.DefaultRequestHeaders.Add("Csrf-Token", _csrfToken); StringContent _bodyContent = new StringContent(_authenticationBody, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage _authResp = await _client.PostAsync(_postURL, _bodyContent); if (_authResp.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception(String.Format("Error: {0}", _authResp.ReasonPhrase)); } else { /* * <?xml version="1.0" encoding="UTF-8"?> * <AuthenticationStatus xmlns="http://citrix.com/deliveryservices/webAPI/2-6/authStatus"> * <Result>success</Result> * <AuthType>Certificate</AuthType> * </AuthenticationStatus> */ string _returnedContent = await _authResp.Content.ReadAsStringAsync(); System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Parse(_returnedContent); //XmlDocument doc = new XmlDocument(); //doc.LoadXml(_returnedContent); //XmlNamespaceManager _namespaceMgr = new XmlNamespaceManager(doc.NameTable); //_namespaceMgr.AddNamespace("mockns", @"http://citrix.com/delivery-services/webAPI/2-6/authStatus"); XNamespace ns = doc.Root.GetDefaultNamespace(); XElement _resultAuthNode = doc.Descendants(ns + "Result").SingleOrDefault(); //XmlNode _resultAuthNode = doc.SelectSingleNode("//mockns:Result", _namespaceMgr); if (_resultAuthNode != null) { //if (_resultAuthNode.InnerText.ToLower() == "success") if (_resultAuthNode.Value.ToLower() == "success") { string _cookiePath = "/"; string _cookieHost = _authResp.RequestMessage.RequestUri.Host; foreach (var header in _authResp.Headers.Where(i => i.Key == "Set-Cookie")) { foreach (string cookieValue in header.Value) { //"ASP.NET_SessionId=miphlcqdo53dwdipdxj3vp4i; path=/; HttpOnly" string[] cookieElements = cookieValue.Split(';'); string[] keyValueElements = cookieElements[0].Split('='); //path //string[] pathCookieElements = cookieElements[1].Split('='); //_cookiePath = pathCookieElements[1]; _returnedValues.Add(keyValueElements[0], keyValueElements[1]); } } _sfCredential = new CitrixAuthCredential { AuthToken = _returnedValues["CtxsAuthId"].ToString(), CSRFToken = _returnedValues["CsrfToken"].ToString(), SessionID = _returnedValues["ASP.NET_SessionId"].ToString(), CookiePath = _cookiePath, CookieHost = _cookieHost }; } } else { _sfCredential = null; } } return(_sfCredential); }