public static async Task<string> HttpGets(string uri) { if (Config.IsNetWork) { NotifyControl notify = new NotifyControl(); notify.Text = "亲,努力加载中..."; notify.Show(); using (HttpClient httpClient = new HttpClient()) { try { HttpResponseMessage response = new HttpResponseMessage(); response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute)); responseString = await response.Content.ReadAsStringAsync(); notify.Hide(); } catch (Exception ex) { Debug.WriteLine(ex.Message.ToString()); } } } return responseString; }
public async Task<bool> SendRequest() { try { var config = new ConfigurationViewModel(); var uri = new Uri(config.Uri + _path); var filter = new HttpBaseProtocolFilter(); if (config.IsSelfSigned == true) { filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); } var httpClient = new HttpClient(filter); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("text/plain")); httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Mozilla", "5.0").ToString())); httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Firefox", "26.0").ToString())); var reponse = await httpClient.GetAsync(uri); httpClient.Dispose(); return reponse.IsSuccessStatusCode; } catch (Exception) { return false; } }
public static async Task<CheckIn> CheckInToEvent(CancellationToken token, int eventId) { var checkIn = new CheckIn(); using (var httpClient = new HttpClient()) { var apiKey = Common.StorageService.LoadSetting("ApiKey"); var apiUrl = Common.StorageService.LoadSetting("ApiUrl"); var profileToken = Common.StorageService.LoadSetting("ProfileToken"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); httpClient.DefaultRequestHeaders.Add("profileToken", profileToken); try { var url = apiUrl + "/api/checkin/event/" + eventId; using (var httpResponse = await httpClient.PostAsync(new Uri(url), null)) { string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token); json = json.Replace("<br>", Environment.NewLine); checkIn = JsonConvert.DeserializeObject<CheckIn>(json); } } catch (Exception e) { } } return checkIn; }
private static string CallService(string token) { var client = new HttpClient(); client.SetBearerToken(token); var response = client.GetStringAsync(new Uri("http://localhost:2727/api/identity")).Result; return response; }
public static void EnsureConnectWifi(string ssidNameSubStr, string id = null, string pw = null) { Task.Run(async() => { while (true) { try { using (var client = new HttpClient()) { var strGoogle = await client.GetStringAsync(new Uri("http://google.com")); } await Task.Delay(3000); } catch (Exception ex) { Log.e($"EX-NETWORK : {ex}"); try { await ConnectWifiAsync(ssidNameSubStr, id, pw); } catch (Exception ex2) { Log.e($"EX-WIFI : {ex2}"); } } } }); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); //string id = ""; string id = string.Empty; if (NavigationContext.QueryString.TryGetValue("id", out id)) { System.Diagnostics.Debug.WriteLine("ID de la pieza: " + id); } HttpClient client = new HttpClient(); string json = await client.GetStringAsync(new Uri("http://museosapp.azurewebsites.net/Piezas/"+id)); _piezas = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Piezas>>(json); //Piezas piezas = NavigateServiceExtends.GetNavigationData(NavigationService) as Piezas; //System.Diagnostics.Debug.WriteLine("PIEZAAAAAAA: " + piezas.descripcion); //piezas.descripcion; //Ésta línea trae toda la información del museo que se ha seleccionado en otro xaml. // Y la muestra en el xaml actual. //this.DataContext = piezas; ElementosQR.ItemsSource = _piezas; loadPieza.Visibility = Visibility.Collapsed; txtCargando.Visibility = Visibility.Collapsed; }
public void ProxyExplicitlyProvided_DefaultCredentials_Ignored() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); var rightCreds = new NetworkCredential("rightusername", "rightpassword"); var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword"); using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds); handler.DefaultProxyCredentials = wrongCreds; Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue); } }
/// <summary> /// Banner,推荐,最新 /// </summary> private async void GetDYHome() { try { pro_Bar.Visibility = Visibility.Visible; using (hc = new HttpClient()) { HttpResponseMessage hr = await hc.GetAsync(new Uri("http://app.bilibili.com/api/region2/23.json")); hr.EnsureSuccessStatusCode(); var encodeResults = await hr.Content.ReadAsBufferAsync(); string results = Encoding.UTF8.GetString(encodeResults.ToArray(), 0, encodeResults.ToArray().Length); DHModel model = JsonConvert.DeserializeObject<DHModel>(results); DHModel model2 = JsonConvert.DeserializeObject<DHModel>(model.result.ToString()); List<DHModel> BannerModel = JsonConvert.DeserializeObject<List<DHModel>>(model2.banners.ToString()); //List<DHModel> RecommendsModel = JsonConvert.DeserializeObject<List<DHModel>>(model2.recommends.ToString()); //List<DHModel> NewsModel = JsonConvert.DeserializeObject<List<DHModel>>(model2.news.ToString()); home_flipView.Items.Clear(); foreach (DHModel item in BannerModel) { if (item.aid != null || item.img != null) { home_flipView.Items.Add(item); } } } pro_Bar.Visibility = Visibility.Collapsed; } catch (Exception ex) { MessageDialog md = new MessageDialog(ex.Message); await md.ShowAsync(); } }
public static async Task<Profile> UpdateProfileAsync(Profile profile) { var authenticatedProfile = await Common.StorageService.RetrieveObjectAsync<Profile>("Profile"); using (var httpClient = new HttpClient()) { var apiKey = Common.StorageService.LoadSetting("ApiKey"); var apiUrl = Common.StorageService.LoadSetting("ApiUrl"); var profileToken = Common.StorageService.LoadSetting("ProfileToken"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); httpClient.DefaultRequestHeaders.Add("profileToken", profileToken); var criteria = new UpdateProfileCriteria { Profile = profile }; var uri = new Uri(apiUrl + "/api/profiles"); var queryString = new HttpStringContent(JsonConvert.SerializeObject(criteria), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync(uri, queryString); string json = await response.Content.ReadAsStringAsync(); json = json.Replace("<br>", Environment.NewLine); profile = JsonConvert.DeserializeObject<Profile>(json); if (profile != null) { await Common.StorageService.PersistObjectAsync("Profile", profile); } } return profile; }
public void CanProxiseByAppid() { var aconfig1 = new HostConfig(); aconfig1.AddQorpentBinding(98); var aconfig2 = new HostConfig(); aconfig2.AddQorpentBinding(99); aconfig2.Proxize["/call1"] = "appid=98"; var h1 = new HostServer(aconfig1); var h2 = new HostServer(aconfig2); h1.On("/call1", "hello!"); var result = ""; try { h1.Start(); h2.Start(); Thread.Sleep(100); result = new HttpClient().GetString("http://127.0.0.1:14990/call1"); } finally { h1.Stop(); h2.Stop(); } Assert.AreEqual("hello!", result); }
public async Task<GithubQueryResult<Repository>> GetRepositoriesAsync(string query, int pageIndex = 1) { if (query == null) { throw new ArgumentNullException(nameof(query)); } if (query.IsBlank()) { throw new ArgumentException("Github query could not be empty.", nameof(query)); } if (pageIndex <= 0) { throw new ArgumentOutOfRangeException(nameof(pageIndex)); } string queryEncoded = WebUtility.UrlEncode(query); string url = string.Format("https://api.github.com/search/repositories?q={0}&page={1}&per_page={2}&order=desc", queryEncoded, pageIndex, PAGE_SIZE); string json; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TryAppendWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240"); json = await client.GetStringAsync(new Uri(url)); } return JsonConvert.DeserializeObject<GithubQueryResult<Repository>>(json); }
public static async void HttpPost(string id,string phone,string image, string name, string content, string time,string atName,string atPhone,string atImage) { try { HttpClient httpClient = new HttpClient(); string posturi = Config.apiCommentPublish; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi)); HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("id",id), new KeyValuePair<string,string>("phone",phone), new KeyValuePair<string, string>("image", image), new KeyValuePair<string, string>("name", name), new KeyValuePair<string, string>("content", content), new KeyValuePair<string, string>("time", time), new KeyValuePair<string, string>("atName", atName), new KeyValuePair<string, string>("atPhone", atPhone), new KeyValuePair<string, string>("atImage", atImage), } ); request.Content = postData; HttpResponseMessage response = await httpClient.SendRequestAsync(request); } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } }
public GPSOAuthClient(string email, string password) { this.email = email; this.password = password; client = new HttpClient(); androidKey = GoogleKeyUtils.KeyFromB64(b64Key); }
public async Task Can_define_custom_parameter_binder() { var client = new HttpClient(); var res = await client.GetAsync("http://localhost:8080/whatipami"); var cont = await res.Content.ReadAsStringAsync(); Assert.Equal("::1", cont); }
public async Task<string> ExecuteAsync() { if (OAuthSettings.AccessToken != null) { return OAuthSettings.AccessToken; } else if (OAuthSettings.RefreshToken == null) { return null; } using (var client = new HttpClient()) { var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>{ {"grant_type","refresh_token"}, {"refresh_token", OAuthSettings.RefreshToken}, {"client_id", OAuthSettings.ClientId}, {"client_secret", OAuthSettings.ClientSecret} }); var response = await client.PostAsync(new Uri(OAuthSettings.TokenEndpoint), content); response.EnsureSuccessStatusCode(); var contentString = await response.Content.ReadAsStringAsync(); var accessTokenInfo = await JsonConvert.DeserializeObjectAsync<OAuthTokenInfo>(contentString); OAuthSettings.AccessToken = accessTokenInfo.AccessToken; OAuthSettings.RefreshToken = accessTokenInfo.RefreshToken; return OAuthSettings.AccessToken; } }
public async Task Automatic_SSLBackendNotSupported_ThrowsPlatformNotSupportedException() { using (var client = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Automatic })) { await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } }
internal static async Task<InternetRequestResult> DownloadAsync(InternetRequestSettings settings) { InternetRequestResult result = new InternetRequestResult(); try { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); if (!string.IsNullOrEmpty(settings.UserAgent)) { httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(settings.UserAgent); } HttpResponseMessage response = await httpClient.GetAsync(settings.RequestedUri); result.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) { FixInvalidCharset(response); result.Result = await response.Content.ReadAsStringAsync(); } } catch (Exception) { result.StatusCode = HttpStatusCode.InternalServerError; result.Result = string.Empty; } return result; }
private static async Task<string> GetRequest(string uri) { try { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(new Uri(uri)); if (!response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.InternalServerError) { throw new Exception(HttpStatusCode.InternalServerError.ToString()); } else { // Throw default exception for other errors response.EnsureSuccessStatusCode(); } } return await response.Content.ReadAsStringAsync(); } } catch (Exception) { if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger System.Diagnostics.Debugger.Break(); } throw; } }
static void CallApi(TokenResponse response) { var client = new HttpClient(); client.SetBearerToken(response.AccessToken); Console.WriteLine(client.GetStringAsync("http://localhost:14869/test").Result); }
public SearchForPlayers(HttpClient Client, StatsDatabase Driver) { string Nick; List<Dictionary<string, object>> Rows; // Setup Params if (!Client.Request.QueryString.ContainsKey("nick")) { Client.Response.WriteResponseStart(false); Client.Response.WriteHeaderLine("asof", "err"); Client.Response.WriteDataLine(DateTime.UtcNow.ToUnixTimestamp(), "Invalid Syntax!"); Client.Response.Send(); return; } else Nick = Client.Request.QueryString["nick"]; // Timestamp Header Client.Response.WriteResponseStart(); Client.Response.WriteHeaderLine("asof"); Client.Response.WriteDataLine(DateTime.UtcNow.ToUnixTimestamp()); // Output status int i = 0; Client.Response.WriteHeaderLine("n", "pid", "nick", "score"); Rows = Driver.Query("SELECT id, name, score FROM player WHERE name LIKE @P0 LIMIT 20", "%" + Nick + "%"); foreach (Dictionary<string, object> Player in Rows) { Client.Response.WriteDataLine(i + 1, Rows[i]["id"], Rows[i]["name"].ToString().Trim(), Rows[i]["score"]); i++; } // Send Response Client.Response.Send(); }
protected override void OnNavigatedTo(NavigationEventArgs e) { HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); meteredConnectionFilter = new HttpMeteredConnectionFilter(baseProtocolFilter); httpClient = new HttpClient(meteredConnectionFilter); cts = new CancellationTokenSource(); }
private static async Task<string> LightColorTask(int hue, int sat, int bri, int Id) { var cts = new CancellationTokenSource(); cts.CancelAfter(5000); try { HttpClient client = new HttpClient(); HttpStringContent content = new HttpStringContent ($"{{ \"bri\": {bri} , \"hue\": {hue} , \"sat\": {sat}}}", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"); //MainPage.RetrieveSettings(out ip, out port, out username); Uri uriLampState = new Uri($"http://{ip}:{port}/api/{username}/lights/{Id}/state"); var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token); if (!response.IsSuccessStatusCode) { return string.Empty; } string jsonResponse = await response.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine(jsonResponse); return jsonResponse; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return string.Empty; } }
public async Task<string> PostStringAsync(string link, string param) { try { System.Diagnostics.Debug.WriteLine(param); Uri uri = new Uri(link); HttpClient httpClient = new HttpClient(); HttpStringContent httpStringContent = new HttpStringContent(param, Windows.Storage.Streams.UnicodeEncoding.Utf8,"application/x-www-form-urlencoded"); //,Windows.Storage.Streams.UnicodeEncoding.Utf8 HttpResponseMessage response = await httpClient.PostAsync(uri, httpStringContent).AsTask(cts.Token); responseHeaders = response.Headers; System.Diagnostics.Debug.WriteLine(responseHeaders); string responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token); return responseBody; } catch(Exception e) { return "Error:" + e.Message; } }
public async Task HttpClient_ClientUsesAuxRecord_Ok() { X509Certificate2 serverCert = Configuration.Certificates.GetServerCertificate(); var server = new SchSendAuxRecordTestServer(serverCert); int port = server.StartServer(); string requestString = "https://localhost:" + port.ToString(); using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { var tasks = new Task[2]; tasks[0] = server.RunTest(); tasks[1] = client.GetStringAsync(requestString); await Task.WhenAll(tasks).TimeoutAfter(15 * 1000); if (server.IsInconclusive) { _output.WriteLine("Test inconclusive: The Operating system preferred a non-CBC or Null cipher."); } else { Assert.True(server.AuxRecordDetected, "Server reports: Client auxiliary record not detected."); } } }
public async Task<Tuple<bool, DateTime?>> SetSessionCookie(string login, string password) { HttpResponseMessage response = null; HttpRequestMessage request = null; using (var httpClient = new HttpClient()) { request = new HttpRequestMessage(HttpMethod.Post, new Uri(Const.UrlLogin)); request.Content = new HttpFormUrlEncodedContent(new[] { new KeyValuePair<string, string>("what", "login"), new KeyValuePair<string, string>("login", login), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("persistent", "true"), }); try { response = await httpClient.SendRequestAsync(request); } catch (Exception) { return new Tuple<bool, DateTime?>(false, null); } } var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); var expireDate = httpFilter.CookieManager.GetCookies(new Uri(Const.UrlFullAddress)).First().Expires ?? DateTime.Now; return new Tuple<bool, DateTime?>(response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok, expireDate.DateTime); }
public async Task<List<Notification>> GetNotifications() { HttpResponseMessage response = null; HttpRequestMessage request = null; using (var httpClient = new HttpClient()) { request = new HttpRequestMessage(HttpMethod.Get, new Uri(Const.UrlNotifyWithTimeStamp)); response = await httpClient.SendRequestAsync(request); } var respList = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); List<Notification> notList = new List<Notification>(); if (respList.HasValues) { var c = respList.First.First; for (int i = 0; i < c.Count(); i++) { var ele = (JProperty)c.ElementAt(i); Notification n = JsonConvert.DeserializeObject<Notification>(ele.Value.ToString()); n.AddedDate = new DateTime(1970, 1, 1).AddMilliseconds((long)(((JValue)ele.Value["Data"]).Value)); n.PublicationId = ele.Name.Split(':')[0]; n.Id = ele.Name.Split(':')[1]; n.TypeValue = Enum.ParseToNotificationType(((JValue)ele.Value["Type"]).Value.ToString()); notList.Add(n); } } notList = notList.OrderBy(n => n.Status).ThenByDescending(n => n.AddedDate).ToList(); return notList; }
static void Main(string[] args) { Uri baseAddress = new Uri("http://*****:*****@gmail.com", PhoneNo = "789" }; Console.WriteLine("\n添加联系人003"); httpClient.PutAsync<Contact>("/api/contacts", contact, new JsonMediaTypeFormatter()).Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); contact = new Contact { Id = "003", Name = "王五", EmailAddress = "*****@*****.**", PhoneNo = "987" }; Console.WriteLine("\n修改联系人003"); httpClient.PostAsync<Contact>("/api/contacts", contact, new XmlMediaTypeFormatter()).Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); Console.WriteLine("\n删除联系人003"); httpClient.DeleteAsync("/api/contacts/003").Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); Console.Read(); }
public override async void receive_file(String devicename, String add, int not) { try { _httpurl = new Uri(add); _httpprogress = new Progress<HttpProgress>(ProgressHandler); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl); HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; _httpclient = new HttpClient(filter); _cancel_token_source = new CancellationTokenSource(); _cancel_token = _cancel_token_source.Token; scan_network_speed(); _stopwatch.Start(); _httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress); StorageFolder folder = KnownFolders.PicturesLibrary; StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting); IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite); IOutputStream filewriter = filestream.GetOutputStreamAt(0); _datawriter = new DataWriter(filewriter); _timer.Cancel(); _transferspeed /= 1024; _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s"); this.callback.on_transfer_speed_change(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); _stopwatch.Stop(); _buffer = await _httpresponse.Content.ReadAsBufferAsync(); _datawriter.WriteBuffer(_buffer); await _datawriter.StoreAsync(); _datawriter.Dispose(); filewriter.Dispose(); filestream.Dispose(); _httpresponse.Content.Dispose(); _httpresponse.Dispose(); _httpclient.Dispose(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, ""); } }
/// <summary> /// upload image and get task's id</summary> /// <param name="data"> byte[], image of document</param> /// <returns> returns UrlData with URL (empty in case of failure) and Status of operation)</returns> public async Task<string> PostImage(byte[] data) { var client = new HttpClient(); setAuthentication(client); string id = ""; client.BaseAddress = new Uri("http://cloud.ocrsdk.com/processMRZ"); try { var response = await client.PostAsync(client.BaseAddress, new ByteArrayContent(data)); response.EnsureSuccessStatusCode(); //Console.WriteLine(response.StatusCode); ///response.isStatusCode != ... ) var result = await response.Content.ReadAsStringAsync(); XmlDocument doc = new XmlDocument(); doc.LoadXml(result); id = doc.SelectSingleNode("/response/task/@id").Value; } catch (Exception exception) { //Console.WriteLine("CAUGHT EXCEPTION:"); //Console.WriteLine(exception); return ""; } return id; }
protected UriTesterBase(HttpClient httpClient, ILogger logger, IRedactor redactor) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _redactor = redactor ?? throw new ArgumentNullException(nameof(redactor)); }
public async Task Get() { var auth = await Request.HttpContext.AuthenticateAsync("OpenIdConnect"); if (!auth.Succeeded || auth?.Principal == null || !auth.Principal.Identities.Any(id => id.IsAuthenticated) || string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token"))) { // Not authenticated, challenge await Request.HttpContext.ChallengeAsync("OpenIdConnect"); } else { //_logger.LogInformation($"principal: {0}", JsonConvert.SerializeObject(auth.Principal)); foreach (var pr in auth.Principal.Identities) { _logger.LogInformation("identity: {0} -> {1} -> {2} -> {3}", pr.Label, pr.NameClaimType, pr.Name, pr.IsAuthenticated); foreach (var cl in pr.Claims) { _logger.LogInformation("claim: {0}-{1}-{2}-{3}", cl.Type, cl.Value, cl.ValueType, cl.Issuer); foreach (var pro in cl.Properties) _logger.LogInformation("prop: {0} -> {1}", pro.Key, pro.Value); } } foreach (var tok in auth.Properties.GetTokens()) _logger.LogInformation($"tok: {tok.Name} -> {tok.Value}"); string run = string.Empty; string name = auth.Principal.FindFirstValue("name"); string email = auth.Principal.FindFirstValue("email"); if (!string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token"))) { try { // obtengamos el userinfo using (var cl = new HttpClient()) { cl.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.Properties.GetTokenValue("access_token")); var ret = await cl.PostAsync("https://www.claveunica.gob.cl/openid/userinfo/", new StringContent(string.Empty)); ret.EnsureSuccessStatusCode(); var json = await ret.Content.ReadAsStringAsync(); _logger.LogInformation("respuesta userinfo: {0}", json); var ui = JsonConvert.DeserializeObject<UserInfo>(json); if (ui?.RolUnico != null) run = $"{ui.RolUnico.Numero}-{ui.RolUnico.DV}"; if (ui?.Name != null) name = string.Join(" ", ui.Name.Nombres) + " " + string.Join(" ", ui.Name.Apellidos); if (!string.IsNullOrEmpty(ui?.Email)) email = ui?.Email; } } catch (Exception e) { _logger.LogError(e, "excepción al obtener UserInfo"); } } var qs = new Dictionary<string, string> { { "access_token", auth.Properties.GetTokenValue("access_token") }, { "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty }, { "expires", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() }, { "run", run }, { "name", name }, { "email", email }, }; // Build the result url var url = callbackScheme + "://#" + string.Join( "&", qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1") .Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}")); // Redirect to final url Request.HttpContext.Response.Redirect(url); } }
public GoDaddyClient(HttpClient httpClient) { _httpClient = new FlurlClient(httpClient); }
public async Task SendBytesBackAndForthBetweenClientAndServer_Success() { using (HttpClient client = CreateHttpClient()) using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var ep = (IPEndPoint)listener.LocalEndPoint; var clientToServerStream = new ProducerConsumerStream(); clientToServerStream.WriteByte(0); var reqMsg = new HttpRequestMessage { RequestUri = new Uri($"http://{ep.Address}:{ep.Port}/"), Content = new StreamContent(clientToServerStream), }; Task <HttpResponseMessage> req = client.SendAsync(reqMsg, HttpCompletionOption.ResponseHeadersRead); using (Socket server = await listener.AcceptAsync()) using (var serverStream = new NetworkStream(server, ownsSocket: false)) { // Skip request headers. while (true) { if (serverStream.ReadByte() == '\r') { serverStream.ReadByte(); break; } while (serverStream.ReadByte() != '\r') { } serverStream.ReadByte(); } // Send response headers. await server.SendAsync( new ArraySegment <byte>(Encoding.ASCII.GetBytes($"HTTP/1.1 200 OK\r\nConnection: close\r\nDate: {DateTimeOffset.UtcNow:R}\r\n\r\n")), SocketFlags.None); HttpResponseMessage resp = await req; Stream serverToClientStream = await resp.Content.ReadAsStreamAsync(); // Communication should now be open between the client and server. // Ping pong bytes back and forth. for (byte i = 0; i < 100; i++) { // Send a byte from the client to the server. The server will receive // the byte as a chunk. if (i > 0) { clientToServerStream.WriteByte(i); // 0 was already seeded when the stream was created above } Assert.Equal('1', serverStream.ReadByte()); Assert.Equal('\r', serverStream.ReadByte()); Assert.Equal('\n', serverStream.ReadByte()); Assert.Equal(i, serverStream.ReadByte()); Assert.Equal('\r', serverStream.ReadByte()); Assert.Equal('\n', serverStream.ReadByte()); // Send a byte from the server to the client. The client will receive // the byte on its own, with HttpClient stripping away the chunk encoding. serverStream.WriteByte(i); Assert.Equal(i, serverToClientStream.ReadByte()); } clientToServerStream.DoneWriting(); server.Shutdown(SocketShutdown.Send); Assert.Equal(-1, clientToServerStream.ReadByte()); } } }
public async System.Threading.Tasks.Task <ICustomActivityResult> Execute() { HttpClient client = new HttpClient(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); UriBuilder UriBuilder = new UriBuilder(endPoint); UriBuilder.Path = uriBuilderPath; UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray); HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString()); if (contentType == "application/x-www-form-urlencoded") { myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData); } else if (string.IsNullOrEmpty(postData) == false) { if (omitJsonEmptyorNull) { myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json"); } else { myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType); } } foreach (KeyValuePair <string, string> headeritem in headers) { client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value); } HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result; switch (response.StatusCode) { case HttpStatusCode.NoContent: case HttpStatusCode.Created: case HttpStatusCode.Accepted: case HttpStatusCode.OK: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) { return(this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath)); } else { return(this.GenerateActivityResult("Success")); } } default: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) { throw new Exception(response.Content.ReadAsStringAsync().Result); } else if (string.IsNullOrEmpty(response.ReasonPhrase) == false) { throw new Exception(response.ReasonPhrase); } else { throw new Exception(response.StatusCode.ToString()); } } } }
protected TestBase(TestFixture fixture) { _jsonSerializerOptions = fixture.JsonSerializerOptions; HttpClient = fixture.HttpClient; }
public FindLicensePlateText(TraceWriter log, HttpClient client) { _log = log; _client = client; }
public HangfireStorageStartupTest(CustomWebApplicationFactory <StartupTest> factory) { _factory = factory; _client = factory.CreateClient(); }
private HttpClientService() { if (HttpClient == null) HttpClient = new HttpClient(); }
public CustomHttpClient(ILogger<CustomHttpClient> logger) { _client = new HttpClient(); _logger = logger; }
public CountryService(HttpClient client) { _client = client; }
public SkipNavigationTest(ODatalizerWebApplicationFactory <Startup> factory) { _client = factory.CreateClient(); }
public HttpService(ICredentialService credentialService, ILogger logger = null) { _logger = logger ?? NullLogger.Instance; _credentialService = credentialService; _httpClient = CreateHttpClient(_credentialService.GetEndpointURL()); }
protected override void ProcessRecord() { Uri tenantUri = null; if (string.IsNullOrEmpty(TenantUrl) && SPOnlineConnection.CurrentConnection != null) { HttpClient client = new HttpClient(); var uri = new Uri(SPOnlineConnection.CurrentConnection.Url); var uriParts = uri.Host.Split('.'); if (uriParts[0].ToLower().EndsWith("-admin")) { tenantUri = new Uri( $"{uri.Scheme}://{uriParts[0].ToLower().Replace("-admin", "")}.{string.Join(".", uriParts.Skip(1))}{(!uri.IsDefaultPort ? ":" + uri.Port : "")}"); } else { tenantUri = new Uri($"{uri.Scheme}://{uri.Authority}"); } } else if (!string.IsNullOrEmpty(TenantUrl)) { tenantUri = new Uri(TenantUrl); } else { throw new InvalidOperationException("Either a connection needs to be made by Connect-PnPOnline or TenantUrl and Credentials needs to be specified"); } var tenantId = Microsoft.SharePoint.Client.TenantExtensions.GetTenantIdByUrl(tenantUri.ToString()); string body; string response; var password = string.Empty; var username = string.Empty; if (MyInvocation.BoundParameters.ContainsKey(nameof(Credentials))) { password = EncryptionUtility.ToInsecureString(Credentials.Password); username = Credentials.UserName; } else if (SPOnlineConnection.CurrentConnection != null) { password = EncryptionUtility.ToInsecureString(SPOnlineConnection.CurrentConnection.PSCredential.Password); username = SPOnlineConnection.CurrentConnection.PSCredential.UserName; } else { throw new InvalidOperationException("Either a connection needs to be made by Connect-PnPOnline or Credentials needs to be specified"); } if (!string.IsNullOrEmpty(Resource)) { body = $"grant_type=password&client_id={ClientId}&username={username}&password={password}&resource={Resource}"; response = HttpHelper.MakePostRequestForString($"https://login.microsoftonline.com/{tenantId}/oauth2/token", body, "application/x-www-form-urlencoded"); } else { var scopes = string.Join(" ", Scopes); body = $"grant_type=password&client_id={ClientId}&username={username}&password={password}&scope={scopes}"; response = HttpHelper.MakePostRequestForString($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token", body, "application/x-www-form-urlencoded"); } var json = JToken.Parse(response); var accessToken = json["access_token"].ToString(); if (SetAsCurrent.IsPresent) { if (SPOnlineConnection.CurrentConnection != null) { SPOnlineConnection.CurrentConnection.AccessToken = accessToken; } else { throw new InvalidOperationException("-SetAsCurrent can only be used when connecting using Connect-PnPOnline"); } } if (Decoded.IsPresent) { var decodedToken = new JwtSecurityToken(accessToken); WriteObject(decodedToken); } else { WriteObject(accessToken); } }
/// <summary> /// Initializes a new instance of the <see cref="FluentClient" /> class. /// </summary> /// <param name="httpClient">The HTTP client.</param> /// <param name="contentSerializer">The content serializer.</param> public FluentClient(HttpClient httpClient, IContentSerializer contentSerializer) { HttpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); ContentSerializer = contentSerializer ?? FluentRest.ContentSerializer.Current; }
public static Task<HttpResponseMessage> SendAsync(this HttpClient client, HttpMethod method, string url, IEnumerable<KeyValuePair<string, string>> parameters, IEnumerable<KeyValuePair<string, string>> headers, string content, string contentType) { return client.SendAsync(method, url, parameters, headers, content == null ? null : Encoding.UTF8.GetBytes(content), contentType); }
public static Task<HttpResponseMessage> SendAsync(this HttpClient client, HttpMethod method, string url) { return client.SendAsync(method, url, null, null); }
public AuditManager(HttpClient httpClient) { _httpClient = httpClient; }
public RestTestService(HttpClient client) { _client = client; }
public static Task<HttpResponseMessage> SendAsync(this HttpClient client, HttpMethod method, string url, IEnumerable<KeyValuePair<string, string>> parameters, IEnumerable<KeyValuePair<string, string>> headers) { return client.SendAsync(method, url, parameters, headers, (byte[])null, "application/x-www-form-urlencoded"); }
private void SetBearerAuthenticationHeader(HttpClient httpClient) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", AccessToken); }
public static async Task DownloadDb(DownloadItem downloadItem) { try { var ext = Android.OS.Environment.ExternalStorageDirectory.Path + "/Downloads"; var rootfolder = FileSystem.Current.LocalStorage; var appfolder = await rootfolder.CreateFolderAsync(ext, CreationCollisionOption.OpenIfExists); var dbfolder = await appfolder.CreateFolderAsync("Db", CreationCollisionOption.OpenIfExists); var file = await dbfolder.CreateFileAsync(downloadItem.FileName, CreationCollisionOption.ReplaceExisting); using (var fileHandler = await file.OpenAsync(FileAccess.ReadAndWrite)) { var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler { CookieContainer = cookieContainer }) using (var client = new HttpClient(handler) { BaseAddress = new Uri(downloadItem.Url) }) { foreach (var header in downloadItem.Headers) { cookieContainer.Add(new Uri(downloadItem.Url), new Cookie(header.Key, header.Value)); } var request = new HttpRequestMessage(HttpMethod.Head, downloadItem.Url); var resp = await client.SendAsync(request); if (resp != null && resp.IsSuccessStatusCode && resp.Content?.Headers?.ContentLength != null) { var dataBuffer = await resp.Content.ReadAsByteArrayAsync(); var dataBuffer1 = await resp.Content.ReadAsStreamAsync(); var dataBuffer2 = resp.Content.LoadIntoBufferAsync(); await fileHandler.WriteAsync(dataBuffer, 0, dataBuffer.Length); } //var resp2 = await client.GetAsync(request.RequestUri.AbsolutePath); //if (resp2.IsSuccessStatusCode) //{ // var content = await resp2.Content.ReadAsByteArrayAsync(); // await fileHandler.WriteAsync(content, 0, content.Length); //} } //var _progressBar = new ProgressBar(); //_progressBar.Progress = 0; //var progressReporter = new Progress<DownloadBytesProgress>(); //progressReporter.ProgressChanged += // (s, args) => _progressBar.Progress = (int) (100 * args.PercentComplete); //var downloadTask = CreateDownloadTask(ImageToDownload, // progressReporter); //var bytesDownloaded = await downloadTask; //Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded); } } catch (Exception ex) { throw ex; } }
public HouseServices() { _httpClient = new HttpClient(); _customerAPI = RestService.For <ICustomerInterface>("https://finalprojectapitest.azurewebsites.net/api"); }
public APIClientProvider() { Client = _factory.CreateClient(); }
private async Task <IQueryResult <T> > ExecuteQuery <T>(QueryOptions options, ITypeSerializer serializer, IRequestSpan span) { var currentContextId = options.CurrentContextId ?? DefaultClientContextId; QueryErrorContext ErrorContextFactory(QueryResultBase <T> failedQueryResult, HttpStatusCode statusCode) { // We use a local function to capture context like options and currentContextId return(new() { ClientContextId = options.CurrentContextId, Parameters = options.GetAllParametersAsJson(), Statement = options.ToString(), Message = GetErrorMessage(failedQueryResult, currentContextId, statusCode), Errors = failedQueryResult.Errors, HttpStatus = statusCode, QueryStatus = failedQueryResult.MetaData?.Status ?? QueryStatus.Fatal }); } // try get Query node var queryUri = _serviceUriProvider.GetRandomQueryUri(); span.WithRemoteAddress(queryUri); using var encodingSpan = span.EncodingSpan(); var body = options.GetFormValuesAsJson(); encodingSpan.Dispose(); _logger.LogDebug("Sending query {contextId} to node {endpoint}.", options.CurrentContextId, queryUri); QueryResultBase <T> queryResult; using var content = new StringContent(body, System.Text.Encoding.UTF8, MediaType.Json); try { using var dispatchSpan = span.DispatchSpan(options); var response = await HttpClient.PostAsync(queryUri, content, options.Token).ConfigureAwait(false); dispatchSpan.Dispose(); var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); if (serializer is IStreamingTypeDeserializer streamingDeserializer) { queryResult = new StreamingQueryResult <T>(stream, streamingDeserializer, ErrorContextFactory); } else { queryResult = new BlockQueryResult <T>(stream, serializer); } queryResult.HttpStatusCode = response.StatusCode; queryResult.Success = response.StatusCode == HttpStatusCode.OK; //read the header and stop when we reach the queried rows await queryResult.InitializeAsync(options.Token).ConfigureAwait(false); if (response.StatusCode != HttpStatusCode.OK || queryResult.MetaData?.Status != QueryStatus.Success) { _logger.LogDebug("Request {currentContextId} has failed because {status}.", currentContextId, queryResult.MetaData?.Status); if (queryResult.ShouldRetry(EnhancedPreparedStatementsEnabled)) { if (queryResult.Errors.Any(x => x.Code == 4040 && EnhancedPreparedStatementsEnabled)) { //clear the cache of stale query plan var statement = options.StatementValue ?? string.Empty; if (_queryCache.TryRemove(statement, out var queryPlan)) { _logger.LogDebug("Query plan is stale for {currentContextId}. Purging plan {queryPlanName}.", currentContextId, queryPlan.Name); } ; } _logger.LogDebug("Request {currentContextId} is being retried.", currentContextId); return(queryResult); } var context = ErrorContextFactory(queryResult, response.StatusCode); if (queryResult.MetaData?.Status == QueryStatus.Timeout) { if (options.IsReadOnly) { throw new AmbiguousTimeoutException { Context = context }; } throw new UnambiguousTimeoutException { Context = context }; } queryResult.ThrowExceptionOnError(context); } } catch (OperationCanceledException e) { var context = new QueryErrorContext { ClientContextId = options.CurrentContextId, Parameters = options.GetAllParametersAsJson(), Statement = options.ToString(), HttpStatus = HttpStatusCode.RequestTimeout, QueryStatus = QueryStatus.Fatal }; _logger.LogDebug(LoggingEvents.QueryEvent, e, "Request timeout."); if (options.IsReadOnly) { throw new UnambiguousTimeoutException("The query was timed out via the Token.", e) { Context = context }; } throw new AmbiguousTimeoutException("The query was timed out via the Token.", e) { Context = context }; } catch (HttpRequestException e) { _logger.LogDebug(LoggingEvents.QueryEvent, e, "Request canceled"); var context = new QueryErrorContext { ClientContextId = options.CurrentContextId, Parameters = options.GetAllParametersAsJson(), Statement = options.ToString(), HttpStatus = HttpStatusCode.RequestTimeout, QueryStatus = QueryStatus.Fatal }; throw new RequestCanceledException("The query was canceled.", e) { Context = context }; } _logger.LogDebug($"Request {options.CurrentContextId} has succeeded."); return(queryResult); }
public static async Task <JArray> GetRowsAsync(string address, string username, string password, string indexname, string elasticFilterField, string elasticFilterValue, string timestampfieldname, DateTime starttime, DateTime endtime) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(address); string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string query; if (elasticFilterField != null && elasticFilterValue != null) { query = "{ \"query\": { \"bool\": { \"must\": [ { \"match_phrase\": { \"" + elasticFilterField + "\": { \"query\": \"" + elasticFilterValue + "\" } } }, { \"range\": { \"" + timestampfieldname + "\": { \"gte\": \"" + starttime.ToString("yyyy-MM-ddTHH:mm:ss.fff") + "\"," + "\"lte\": \"" + endtime.ToString("yyyy-MM-ddTHH:mm:ss.fff") + "\" } } } ] } } }"; } else { query = "{ \"query\": { \"range\": { \"" + timestampfieldname + "\": { \"gte\": \"" + starttime.ToString("yyyy-MM-ddTHH:mm:ss.fff") + "\", \"lte\": \"" + endtime.ToString("yyyy-MM-ddTHH:mm:ss.fff") + "\" } } } }"; } string url = $"{indexname}/_search?size=10000"; Log($"url: >>>{url}<<<"); Log($"body: >>>{query}<<<"); WriteLogMessage(query, "post"); var response = await client.PostAsync(url, new StringContent(query, Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); string result = await response.Content.ReadAsStringAsync(); WriteLogMessage(result, "result"); if (result.Length > 0) { dynamic hits = JObject.Parse(result); return((JArray)hits.hits.hits); } } return(null); }
/// <summary> /// Initializes a new instance of the <see cref="FluentClient" /> class. /// </summary> /// <param name="httpClient">The HTTP client.</param> public FluentClient(HttpClient httpClient) : this(httpClient, null) { }
//Método responsável por buscar os dados do veículo direto do site do governo private async Task <List <VeiculoModel> > ObterVeiculosTabelaFipe(CatalogoContext catalogoContext, string Referencia, int Ano) { //Configuração de proxy //Remover ou configurar de acordo com a necessidade HttpClient httpClient = new HttpClient(new HttpClientHandler() { UseProxy = true, Proxy = null, // use system proxy DefaultProxyCredentials = new System.Net.NetworkCredential("fabio.souza", "fs123456") }); //Retorna as tabelas de referência var resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarTabelaDeReferencia", null); //Cria uma lista de veículos List <VeiculoModel> lista = new List <VeiculoModel>(); //Se o retorno é bem sucedido, prossegue if (resposta.IsSuccessStatusCode) { //Lê o conteúdo da resposta List <JObject> conteudo = await resposta.Content.ReadAsAsync <List <JObject> >(); //Retorna o código da tabela de acordo com o ano informado var codigo_tabela = conteudo.Where(e => e.GetValue("Mes").ToString().Replace(" ", "") == Referencia).Select(e => e.GetValue("Codigo").ToString()).FirstOrDefault(); //Se o código não é nulo, prossegue if (codigo_tabela != null) { //Cria os parâmetros para a próxima requisição var pairs = new List <KeyValuePair <string, string> >(); pairs.Add(new KeyValuePair <string, string>("codigoTabelaReferencia", codigo_tabela)); pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1")); //cria o corpo da requisição var body = new FormUrlEncodedContent(pairs); //Retorna as marcas de acordo com a tabela de referência resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarMarcas", body); var marcas = await resposta.Content.ReadAsAsync <List <JObject> >(); //Percorre as marcas for (var i = 0; i < marcas.Count; i++) { //Cria os parâmetros para a próxima requisição pairs = new List <KeyValuePair <string, string> >(); pairs.Add(new KeyValuePair <string, string>("codigoTabelaReferencia", codigo_tabela)); pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1")); pairs.Add(new KeyValuePair <string, string>("codigoMarca", marcas[i].GetValue("Value").ToString())); //cria o corpo da requisição body = new FormUrlEncodedContent(pairs); //Retorna os modelos de acordo com a tabela de referência e marca resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarModelos", body); JObject Ano_Modelos = await resposta.Content.ReadAsAsync <JObject>(); List <JObject> Modelos = Ano_Modelos.GetValue("Modelos").ToObject <List <JObject> >(); //Percorre os modelos for (var m = 0; m < Modelos.Count; m++) { //Cria os parâmetros para a próxima requisição pairs = new List <KeyValuePair <string, string> >(); pairs.Add(new KeyValuePair <string, string>("codigoTabelaReferencia", codigo_tabela)); pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1")); pairs.Add(new KeyValuePair <string, string>("codigoMarca", marcas[i].GetValue("Value").ToString())); pairs.Add(new KeyValuePair <string, string>("codigoModelo", Modelos[m].GetValue("Value").ToString())); pairs.Add(new KeyValuePair <string, string>("anoModelo", Ano.ToString())); pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1")); pairs.Add(new KeyValuePair <string, string>("codigoTipoCombustivel", "1")); pairs.Add(new KeyValuePair <string, string>("tipoConsulta", "tradicional")); pairs.Add(new KeyValuePair <string, string>("tipoVeiculo", "carro")); //cria o corpo da requisição body = new FormUrlEncodedContent(pairs); //Retorna os dados do veículo de acordo com a tabela de referência, marca, modelo e ano do modelo resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarValorComTodosParametros", body); JObject Veiculo = await resposta.Content.ReadAsAsync <JObject>(); //Se o veículo é encontrado e possui valor, prossegue if (Veiculo != null) { if (Veiculo.Property("Valor") != null) { var style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands; var provider = new CultureInfo("pt-BR"); string valor = Veiculo.GetValue("Valor").ToString(); valor = valor.Replace("R$ ", "").Replace(".", ""); VeiculoModel veiculoModel = new VeiculoModel() { AnoModelo = short.Parse(Veiculo.GetValue("AnoModelo").ToString()), CodigoFipe = Veiculo.GetValue("CodigoFipe").ToString(), Marca = Veiculo.GetValue("Marca").ToString(), Modelo = Veiculo.GetValue("Modelo").ToString(), PrecoMedio = Decimal.Parse(valor, style, provider), Referencia = Referencia }; //Adiciona o veículo no banco de dados var result = await Adicionar(catalogoContext, veiculoModel); //Se é adicionado com sucesso, adiciona na lista if (result.GetType() == typeof(VeiculoModel)) { veiculoModel = (VeiculoModel) await Adicionar(catalogoContext, veiculoModel); lista.Add(veiculoModel); } //Limitado a 10 pois o processo leva muito tempo if (lista.Count >= 10) { return(lista); } } } } } } } //Retorna a lista return(lista); }
public async Task<bool> TryStartTelegram() { using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. bool ret = true; try { if (AppSettings.Settings.telegram_token.IsNotNull() && AppSettings.Settings.telegram_chatids.IsNotEmpty()) { if (!this.Started.ReadFullFence()) { Log("Debug: Initializing Telegram Bot..."); Stopwatch sw = Stopwatch.StartNew(); //try to prevent telegram Could not create SSL/TLS secure channel exception on Win7. //This may also need TLS 1.2 and 1.3 checked in Internet Options > Advanced tab.... ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; this.telegramHttpClient = new System.Net.Http.HttpClient(); this.telegramHttpClient.Timeout = TimeSpan.FromSeconds(AppSettings.Settings.HTTPClientRemoteTimeoutSeconds); this.telegramBot = new TelegramBotClient(AppSettings.Settings.telegram_token, this.telegramHttpClient); //this may be redundant: this.telegramBot.Timeout = TimeSpan.FromSeconds(AppSettings.Settings.HTTPClientRemoteTimeoutSeconds); //for debugging, remove later... this.telegramBot.OnApiResponseReceived += TelegramBot_OnApiResponseReceived; this.telegramBot.OnMakingApiRequest += TelegramBot_OnMakingApiRequest; //start another thread to initialize listening for commands (said it was non blocking but was having weird issues with it) if (!this.StartingReceive.ReadFullFence()) { //Only start listening if another instance is not running if (!AppSettings.AlreadyRunning && AppSettings.Settings.telegram_monitor_commands) Task.Run(TelegramStartReceiving); } else Log($"Debug: Already initializing StartReceiving?"); Log($"Debug: ...Done in {sw.ElapsedMilliseconds}ms."); this.Started.WriteFullFence(true); } } else { Log("Debug: Telegram Bot cannot initialize because of missing token or chatid."); } } catch (Exception ex) { ret = false; this.Started.WriteFullFence(false); throw; } return ret; }
public async Task <ActionResult> EditProduct(ProductUpdateForm formDATA) { var ProductDetails = new JavaScriptSerializer().Deserialize <TBL_Products>(formDATA.ProductDetails); UserDetails currentUser = GetCurrentUserDetails(); AddProductViewModel model = new AddProductViewModel(); model.ProductDetails = ProductDetails; if (formDATA.file != null) { model.ProductImages = new List <TBL_ProductImages>(); model.ProductImages.Add(new TBL_ProductImages() { ImageID = CommonSafeConvert.ToInt(formDATA.imgId), ProductID = ProductDetails.ProductID, UpdatedBy = currentUser.UserId, UpdateDate = DateTime.Now, IsActive = true, ProductImage = CommonSafeConvert.ConvertToBytesFromFile(formDATA.file) }); } if (ModelState.IsValid) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(WebAppConfig.GetConfigValue("WebAPIUrl")); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var response = new CommonAjaxCallToWebAPI().AjaxPost("/api/product/PostEditProduct", model, Convert.ToString(Session["BSWebApiToken"])).Result; // var response = await client.PostAsJsonAsync("/api/product/PostEditProduct", model); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var rslt = await response.Content.ReadAsStringAsync(); var reslt = new JavaScriptSerializer().Deserialize <BSEntityFramework_ResultType>(rslt); if (reslt.Result == BSResult.FailForValidation) { foreach (var valerr in reslt.EntityValidationException) { ModelState.AddModelError("BS Errors", valerr); } } //return reslt; //FillViewDatasForAddShop(); var allErrors = ModelState.Values.SelectMany(v => v.Errors); return(Json(allErrors, JsonRequestBehavior.AllowGet)); } else { return(Json("Failed", JsonRequestBehavior.AllowGet)); } } } return(Json(new { Valid = ModelState.IsValid, UserID = currentUser.UserId, Errors = GetErrorsFromModelState(), Status = "Validation Failed" })); }
private async static void UriSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { Debug.WriteLine("我被触发了"); StorageCachedImage image = d as StorageCachedImage; string i = e.NewValue as string; int k = i.IndexOf("image"); string imagePath = i.Substring(k + 7); string uri = App.Uri + "public/images/" + imagePath; Debug.WriteLine(uri); Uri imageUri = new Uri(uri); HttpClient client = new HttpClient(); var response = await client.GetAsync(imageUri); var buffer = await response.Content.ReadAsBufferAsync(); var memoryStream = new InMemoryRandomAccessStream(); await memoryStream.WriteAsync(buffer); await memoryStream.FlushAsync(); await image.SetSourceAsync(memoryStream); }