public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location, UserAccountEntity userAccountEntity) { if (userAccountEntity.GetAccessToken().Equals("refresh")) { await Auth.RefreshAccessToken(userAccountEntity); } var param = new Dictionary<String, String>(); if (!string.IsNullOrEmpty(name)) param.Add("name", name); if (!string.IsNullOrEmpty(url)) param.Add("url", url); if (!string.IsNullOrEmpty(location)) param.Add("location", location); if (!string.IsNullOrEmpty(description)) param.Add("description", description); var theAuthClient = new HttpClient(); HttpContent header = new FormUrlEncodedContent(param); var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header}; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken()); try { HttpResponseMessage response = await theAuthClient.SendAsync(request); return response.IsSuccessStatusCode; } catch (Exception) { return false; } }
public bool InsertFile(FileStruct file) { try { using (var client = new HttpClient()) { client.BaseAddress = new Uri(RequestUri.BaseUrl); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("vkFileId", file.vkFileId.ToString()), new KeyValuePair<string, string>("filename", file.filename), new KeyValuePair<string, string>("dialog", file.dialogId), new KeyValuePair<string, string>("tags", string.Join(",",file.tags)) }); var result = client.PostAsync(RequestUri.InsertFileRequestUri, content).Result; string resultContent = result.Content.ReadAsStringAsync().Result; return true; } } catch { return false; } }
/// <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; } }
public async Task <bool> AuthorizeAsync(string userNameOrEmail, string password, int?validityInHours = null) { using (var dclient = this.clientFactory()) { var client = dclient.Client; var keyValues = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("UserName", userNameOrEmail), new KeyValuePair <string, string>("Password", password) }; if (validityInHours.HasValue) { keyValues.Add(new KeyValuePair <string, string>("ValidityInHours", validityInHours.Value.ToString())); } var content = new System.Net.Http.FormUrlEncodedContent(keyValues); var response = await client.PostAsync(new Uri(new Uri(BaseUrl), ApiUrls.AuthorizeUrl), content).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { return(false); } if (response.Headers.Any(c => c.Key == ApiUrls.AuthorizeTokenHeaderName) == false) { return(false); } var token = response.Headers.Where(c => c.Key == ApiUrls.AuthorizeTokenHeaderName) .First() .Value.First() .ToString() ; this.SetToken(token); return(true); } }
public RecaptchaResponse Validate(RecaptchaRequest recaptchaRequest) { var result = new RecaptchaResponse { Success = false }; var request = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("secret", _configurationManager.GetAppSettingAs<string>(AppSettingsRecaptchaSecretKey)), new KeyValuePair<string, string>("response", recaptchaRequest.Token), new KeyValuePair<string, string>("remoteip", recaptchaRequest.IpAddress) }); var response = _client.PostAsync(ApiUrl, request).Result; if (response.IsSuccessStatusCode) { var contents = response.Content.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(contents)) { result = JsonConvert.DeserializeObject<RecaptchaResponse>(contents, new StringEnumConverter()); } } return result; }
public ActionResult PostWhoAmI(string tenantKey, string authToken) { string url = "api/v1.0/Contacts/WhoAmI"; HttpClient client = new HttpClient(); client.BaseAddress = new Uri("https://api.connectedcommunity.org/"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("HLTenantKey", tenantKey); client.DefaultRequestHeaders.Add("HLAuthToken", authToken); var content = new System.Net.Http.FormUrlEncodedContent(new[] { new KeyValuePair <string, string>() }); JObject results = null; string whoAmI = null; HttpResponseMessage response = client.PostAsync(url, content).Result; if (response.IsSuccessStatusCode) { results = JsonConvert.DeserializeObject <dynamic>(response.Content.ReadAsStringAsync().Result); whoAmI = JsonConvert.SerializeObject(results, Formatting.Indented); } else { return(RedirectToAction("UserSignIn", "Domain", new { preView = "PostWhoAmI" })); } ViewData["results"] = results; ViewData["whoAmI"] = whoAmI; return(View()); }
static public void write_dump(string desc) { string fname = "MiniDmp_" + DateTime.Now.ToString("yyyy-MM-dd_hh_mm_ss") + ".dmp"; MessageBox.Show("发生未知错误,崩溃了,请将此窗口截图发送;如有必要,也请发送" + fname + " 以便修错误\r\n " + desc); var dic = new Dictionary <string, string>(); dic["msg"] = desc; var c = new System.Net.Http.FormUrlEncodedContent(dic); try { var p = new System.Net.Http.HttpClient(); var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/logerror", c).Result; } catch (Exception) { } using (FileStream fs = new FileStream(fname, FileMode.Create, FileAccess.ReadWrite, FileShare.Write)) { MiniDump.Write(fs.SafeFileHandle, MiniDump.Option.Normal); } }
public async Task<JObject> Execute() { if (!NetworkInterface.GetIsNetworkAvailable()) throw new Exception("Network is not available."); var uri = GetFullUri(); #if DEBUG Debug.WriteLine("Invoking " + uri); #endif JObject response = null; var httpClient = new HttpClient(); if (_method == "GET") { HttpResponseMessage responseMessage = await httpClient.GetAsync(uri); var content = await responseMessage.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(content)) response = JObject.Parse(content); } else { var postContent = new FormUrlEncodedContent(_parameters); postContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage responseMessage = await httpClient.PostAsync(uri, postContent); var content = await responseMessage.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(content)) response = JObject.Parse(content); } return response; }
async Task<string> GetAuthToken(bool forceFetch = false) { if (!forceFetch && lastTokenFetch > DateTime.Now - TimeSpan.FromHours(48)) { return token; } var pairs = new Dictionary<string, string> { { "username", username }, { "password", password } }; var content = new FormUrlEncodedContent(pairs); var response = await client.PostAsync(AuthUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); var jsonResponse = JObject.Parse(responseContent); if (jsonResponse["error"] != null) { throw new ApplicationException((string)jsonResponse["error"]); } token = (string)jsonResponse["token"]; lastTokenFetch = DateTime.Now; return token; }
public Step CheckStatusCodeIs(HttpStatusCode codeToMatch) { var formContent = new FormUrlEncodedContent(_formContent); SetUpDefaultHeaders(); Stopwatch stopWatch = Stopwatch.StartNew(); var task = Post(formContent); string htmlContent = task.Result.Content.ReadAsStringAsync().Result; stopWatch.Stop(); Console.WriteLine("Took {0} Milliseconds", stopWatch.ElapsedMilliseconds); if (!string.IsNullOrEmpty(htmlContent)) { if (htmlContent.Contains("__EVENTVALIDATION")) { CurrentEventValidation = HttpScraper.GetEventValidationFromHtml(htmlContent); } if (htmlContent.Contains("__VIEWSTATE")) { CurrentViewState = HttpScraper.GetViewStateFromHtml(htmlContent); } } if (task.Result != null) { task.Result.StatusCode.Should().Be(codeToMatch); } else { throw new Exception("Http Status code is null"); } Step.CurrentEventValidation = CurrentEventValidation; Step.CurrentViewState = CurrentViewState; Step.CurrentHtml = htmlContent; Dispose(); return Step; }
public static async Task<bool> SendCommentReply(string userId,string comment) { try { var client = await MalHttpContextProvider.GetHttpContextAsync(); var contentPairs = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("profileMemId", userId), new KeyValuePair<string, string>("commentText", comment), new KeyValuePair<string, string>("area", "2"), new KeyValuePair<string, string>("csrf_token", client.Token), new KeyValuePair<string, string>("commentSubmit", "1") }; var content = new FormUrlEncodedContent(contentPairs); var response = await client.PostAsync("/addcomment.php", content); //edit comment function - not sure what it does // /includes/ajax.inc.php?t=73 //com id - token //id = 31985758 & csrf_token = dfsdfsd //client.PostAsync("/includes/ajax.inc.php?t=73") return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.SeeOther; } catch (WebException) { MalHttpContextProvider.ErrorMessage("Messages"); return false; } }
public void Authenticate( OauthAuthorization authorization) { logger.Debug("Authenticating twitter client"); this.authorization = authorization; string encodedKey = EncodeConsumerKeyAndSecret(authorization.ConsumerKey,authorization.ConsumerSecret); // create request var keyValuePair = new KeyValuePair<string, string>("grant_type", "client_credentials"); HttpContent httpContent = new FormUrlEncodedContent(new Collection<KeyValuePair<string, string>>(){keyValuePair}); httpContent.Headers.ContentType.CharSet = "UTF-8"; this._client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); this._client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedKey); // post request HttpResponseMessage postAsync = _client.PostAsync("/oauth2/token", httpContent).Result; HandleErrors(postAsync); // Get access token Stream readAsStringAsync = postAsync.Content.ReadAsStreamAsync().Result; string json = Decompress(readAsStringAsync); this._accessToken = JsonConvert.DeserializeObject<AccessToken>(json); this._client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(this._accessToken.token_type, this._accessToken.access_token); logger.Debug("Authenticated"); }
public double GET(string uid) { bool t = true; double unique; do { var client = new HttpClient(); client.BaseAddress = new Uri("http://api.text.ru"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("uid", uid), new KeyValuePair<string, string>("userkey", Key), }); var result = client.PostAsync("/post", content).Result; string resultContent = result.Content.ReadAsStringAsync().Result; var res = JsonConvert.DeserializeObject<Plagiarism>(resultContent); unique = res.uniq; int error = res.err; if (error == 181) { t = false; Thread.Sleep(10000); } else t = true; } while (!t); Repository.Work.Plag = unique; return unique; }
/// <summary> /// オンラインから非同期でランキングデータを取得するメソッド /// </summary> /// <returns>サーバーから受信したランキングデータをJSON化したもの, もしくはサーバーから返信されたエラーメッセージ</returns> private async Task <string> SendOnlieGetData(bool isAll = false) { String lim; if (isAll) { lim = 0.ToString(); } else { lim = RankingManager.limit.ToString(); } Dictionary <String, String> postid = new Dictionary <String, String> { { "GameID", RankingData.GameID.ToString() }, { "OrderType", RankingManager.Oder.ToString() }, { "Limit", lim } }; var content = new System.Net.Http.FormUrlEncodedContent(postid); var client = new System.Net.Http.HttpClient(); Log.Info("【Online】Access to server."); Log.Info($"【Online】Address is [{BaseUrl}{GET_DATA_URL}]."); foreach (KeyValuePair <String, String> pair in postid) { Log.Info($"【Online】【Transmission】Contents key = [{pair.Key}], value = [{pair.Value}]."); } Log.Info($"【Online】【Transmission】Contents [{content.Headers.ContentDisposition}]."); var response = await client.PostAsync(BaseUrl + GET_DATA_URL, content); return(await response.Content.ReadAsStringAsync()); }
/// <summary> /// Makes a HTTP call to the OAuth2 endpoint for getting the OAuth2 token that can be used for /// further HTTP communication with Dinero. /// </summary> /// <returns></returns> public async Task<AuthorizationToken> GetAuthorizationToken() { var clientInfo = _client.Id + ":" + _client.Secret; using (var client = new HttpClient()) { var content = new FormUrlEncodedContent(_bodyContentParameters.GetBodyParameters()); var request = new HttpRequestMessage { RequestUri = _oAuth2TokenEndpoint, Method = HttpMethod.Post, Content = content }; request.Headers.Add("Authorization", string.Format("Basic {0}", clientInfo.Base64Encode())); var result = await client.SendAsync(request).ConfigureAwait(false); var resultContent = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var definition = new { Access_Token = "", Token_Type = "", Expires_In = 0, Refresh_Token = ""}; try { var resultObj = JsonConvert.DeserializeAnonymousType(resultContent, definition); if (resultObj.Access_Token == null) throw new DineroAuthenticationException("Could not retrieve access token."); return new AuthorizationToken(resultObj.Access_Token, DateTime.Now.AddSeconds(resultObj.Expires_In).AddMinutes(-5), resultObj.Refresh_Token); } catch (Exception e) { throw new DineroAuthenticationException("Could not retrieve access token.",e); } } }
public static async Task<bool> ChkVerifyCodeAnsyn(string verifyNo) { try { var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip }; using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn"); httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin); httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer); httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131"); ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true; // 构造POST参数 var data = new FormUrlEncodedContent(new Dictionary<string, string>() { {"randCode", verifyNo}, {"rand", "sjrand"} }); var response = await httpClient.PostAsync(ConstantKey.loginChkVcode, data); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); if (string.IsNullOrEmpty(content) || !content.Contains("Y") || !content.Contains("true")) return false; return true; } } catch (Exception ex) { return false; } }
public static async Task<bool> UpdateStatus(String status, long? inReply, bool? inQuote, bool? trim, UserAccountEntity userAccountEntity) { var param = new Dictionary<String, String> {{"status", status}}; if (inReply != null) param.Add("in_reply_to_status_id", inReply.ToString()); if (inQuote == true) param.Add("in_reply_with_quote", true.ToString()); if (trim == true) param.Add("trim_user", true.ToString()); var theAuthClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.STATUS_UPDATE); string accessToken = userAccountEntity.GetAccessToken(); if (accessToken.Equals("refresh")) { await Auth.RefreshAccessToken(userAccountEntity); accessToken = userAccountEntity.GetAccessToken(); } HttpContent header = new FormUrlEncodedContent(param); request.Content = header; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); try { HttpResponseMessage response = await theAuthClient.SendAsync(request); return response.IsSuccessStatusCode; } catch (Exception) { return false; } }
public async void SimpleAsyncPost() { System.Collections.Generic.Dictionary <string, string> values = new System.Collections.Generic.Dictionary <string, string>(); values.Add("ThisIs", "Annoying"); System.Net.Http.FormUrlEncodedContent content = new System.Net.Http.FormUrlEncodedContent(values); using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { try { System.Net.Http.HttpResponseMessage httpResponseMessage = await client.PostAsync("http://SomeUrl.somewhere", content); if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK) { // Do something... } } catch (System.OperationCanceledException opc) { System.Console.WriteLine(opc); } } }
private async Task <OAuth2Token> RequestToken_RefreshTokenGrant(HttpClient client, OAuth2Token token, HttpRequestMessage request) { using (var creds = await _Settings.ClientCredentialProvider.GetCredentials().ConfigureAwait(false)) { var values = new Dictionary <string, string>(4); values.Add("grant_type", OAuth2GrantTypes.RefreshToken); values.Add("refresh_token", token.RefreshToken); values.Add("scope", _Settings.Scope); var state = _Settings?.State?.Invoke(request); if (state != null) { values.Add("state", state); } var content = new System.Net.Http.FormUrlEncodedContent(values); var tokenResult = await client.PostAsync(_Settings.AccessTokenUrl, content).ConfigureAwait(false); try { return(await ProcessTokenResponse(tokenResult).ConfigureAwait(false)); } catch { #if DEBUG throw; #else //On an error, attempt to get a new token rather than refreshing one. _Token = null; return(await AcquireToken(request)); #endif } } }
private async void button_Click(object sender, RoutedEventArgs e) { String Antwort = ""; string Ziel = "/Nachricht.php?"; HttpContent content = new FormUrlEncodedContent(new[] // POST inhalt vorbereiten { new KeyValuePair<string, string>("NachrichtHead", GlobalData.Pers_ID), new KeyValuePair<string, string>("Betreff",textBox1.Text), new KeyValuePair<string, string>("inhalt", textBox.Text), }); // Schritt 4 Abfrage abschicken und ergebnis entgegennehmen try { Antwort = await Globafunctions.HttpAbfrage(Ziel, content); } catch { MessageDialog msgbox = new MessageDialog("Nachricht konnte nicht Versendet werden"); await msgbox.ShowAsync(); } MessageDialog msgbox1 = new MessageDialog(Antwort); await msgbox1.ShowAsync(); Frame.Navigate(typeof(Intern)); }
public async Task ApplyConfiguration(JToken configJson) { var config = new ConfigurationDataBasicLogin(); config.LoadValuesFromJson(configJson); var pairs = new Dictionary<string, string> { { "username", config.Username.Value }, { "password", config.Password.Value } }; var content = new FormUrlEncodedContent(pairs); var response = await client.PostAsync(LoginUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); if (!responseContent.Contains("logout.php")) { CQ dom = responseContent; var errorMessage = dom["td.text"].Text().Trim(); throw new ExceptionWithConfigData(errorMessage, (ConfigurationData)config); } else { var configSaveData = new JObject(); cookies.DumpToJson(SiteLink, configSaveData); SaveConfig(configSaveData); IsConfigured = true; } }
async public Task <CookieContainer> getAccountCookie(string mail, string pass) { if (mail == null || pass == null) { return(null); } var isNew = true; string loginUrl; Dictionary <string, string> param; if (isNew) { loginUrl = "https://account.nicovideo.jp/login/redirector"; param = new Dictionary <string, string> { { "mail_tel", mail }, { "password", pass }, { "auth_id", "15263781" } //dummy }; } else { loginUrl = "https://secure.nicovideo.jp/secure/login?site=nicolive"; param = new Dictionary <string, string> { { "mail", mail }, { "password", pass } }; } try { var handler = new System.Net.Http.HttpClientHandler(); if (util.httpProxy != null) { handler.UseProxy = true; handler.Proxy = util.httpProxy; } handler.UseCookies = true; var http = new System.Net.Http.HttpClient(handler); var content = new System.Net.Http.FormUrlEncodedContent(param); var _res = await http.PostAsync(loginUrl, content); var res = await _res.Content.ReadAsStringAsync(); var cc = handler.CookieContainer; var cookies = cc.GetCookies(TargetUrl); var c = cookies["user_session"]; var secureC = cookies["user_session_secure"]; //cc = copyUserSession(cc, c, secureC); log += (c == null) ? "ユーザーセッションが見つかりませんでした。" : "ユーザーセッションが見つかりました。"; log += (secureC == null) ? "secureユーザーセッションが見つかりませんでした。" : "secureユーザーセッションが見つかりました。"; if (c == null && secureC == null) { return(null); } return(cc); } catch (Exception e) { util.debugWriteLine(e.Message + e.StackTrace); return(null); } }
public override async Task<string> GetTokenFromGrant(string grant) { string token = ""; using (var client = new HttpClient()) { Dictionary<string, string> postvalues = new Dictionary<string, string> { { "code", grant }, { "client_id", AppID }, { "client_secret", AppSecret }, { "redirect_uri", RedirectURI }, { "grant_type", "authorization_code" } }; var content = new FormUrlEncodedContent(postvalues); var response = await client.PostAsync("https://www.googleapis.com/oauth2/v4/token", content); var responseString = await response.Content.ReadAsStringAsync(); Dictionary<string, string> responseJSON = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString); token = responseJSON["access_token"]; } return token; }
public async Task<OperationResult<accessToken>> GetAccessTocken(string UserName, string PassWord) { StringBuilder requestUrl = new StringBuilder(url + "/token"); Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("username", UserName); parameters.Add("password", PassWord); parameters.Add("grant_type", grant_type); FormUrlEncodedContent content = new FormUrlEncodedContent(parameters); var result = await client.PostAsync(requestUrl.ToString(), content); if (result.StatusCode != HttpStatusCode.OK) { var Jsonerr = result.Content.ReadAsStringAsync().Result; var err = JsonConvert.DeserializeObject<error_state>(Jsonerr); return new OperationResult<accessToken>() { err_code = ErrorEnum.sys_error, err_info = err.error + " " + err.error_description }; } var Json = result.Content.ReadAsStringAsync().Result; var token = JsonConvert.DeserializeObject<accessToken>(Json); return new OperationResult<accessToken>() { err_code = ErrorEnum.success, err_info = ErrorEnum.success.ToString(), entity = token }; }
private async Task<SuccessfulAuthenticationResponse> GetAuthorizationCode(AuthorizationGrantRequest request) { var url = request.Uri; var data = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("scope", "openid"), new KeyValuePair<string, string>("response_type", "code"), new KeyValuePair<string, string>("client_id", request.ClientId), new KeyValuePair<string, string>("client_secret", request.ClientSecret), new KeyValuePair<string, string>("prompt", "none"), new KeyValuePair<string, string>("redirect_uri", request.RedirectUri), new KeyValuePair<string, string>("username", request.Username), new KeyValuePair<string, string>("password", request.Password), }); var client = new HttpClient(); var response = await client.PostAsync(url, data); var content = await response.Content.ReadAsStringAsync(); if (response.StatusCode != System.Net.HttpStatusCode.OK) { var error = JsonConvert .DeserializeObject<AuthenticationErrorResponse> (content); throw new Exception(error.error + ": " + error.error_description); } else { return JsonConvert .DeserializeObject<SuccessfulAuthenticationResponse> (content); } }
private async Task<SuccessfulTokenResponse> GetTokenId(AuthorizationGrantRequest request, string code) { var client = new HttpClient(); var url = $"{request.Uri}token"; var data = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("username", request.Username), new KeyValuePair<string, string>("password", request.Password), new KeyValuePair<string, string>("grant_type", "authorization_code"), new KeyValuePair<string, string>("code", code), new KeyValuePair<string, string>("redirect_uri", request.RedirectUri) }); var response = await client.PostAsync(url, data); var content = await response.Content.ReadAsStringAsync(); if (response.StatusCode != System.Net.HttpStatusCode.OK) { var error = JsonConvert .DeserializeObject<AuthenticationErrorResponse> (content); throw new Exception(error.error + ": " + error.error_description); } else { return JsonConvert .DeserializeObject<SuccessfulTokenResponse> (content); } }
private void PopulateDefenseData(string forumId, PlayerAnalytics analytics) { string html; using (var httpClient = new HttpClient()) { var values = new Dictionary <string, string> { { "season", TargetSeason }, { "button", "view+season" } }; var content = new System.Net.Http.FormUrlEncodedContent(values); var response = httpClient.PostAsync("http://xbox-sports.com/leagues/xbshl/index.php?mode=player&filter_pos=defense&player_id=" + forumId, content).GetAwaiter().GetResult(); html = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); } HtmlDocument document = new HtmlDocument(); document.LoadHtml(html); var statsItems = document.DocumentNode.Descendants().Where(x => x.HasClass("row_1g_h") || x.HasClass("row_1f_h")); foreach (var item in statsItems) { int season = Int32.Parse(item.Descendants().FirstOrDefault(x => x.HasClass("color_2a")).InnerText.Split(' ')[1]); if (season < _minimumSeasonThreshold) // Who cares about older seasons { continue; } var childCells = item.ChildNodes.Where(x => x.Name == "td").ToArray(); //1 = GP, 2= G, 3 = A, 4=pts, 5=pim, 6 = hits, 7 = shots, 8 = gwgm 9 = fo%, 10 = +\-, 11=corsi, 12 = wins, 13 = losses, 14 = OTL var statsObj = new DefenseStatistics(); statsObj.Season = season; var teamNames = childCells[0].Descendants().Where(x => x.Name == "a"); foreach (var name in teamNames) { statsObj.TeamNames.Add(name.InnerText); } statsObj.GamesPlayed = Int32.Parse(childCells[1].InnerText); statsObj.Goals = Int32.Parse(childCells[2].InnerText); statsObj.Assists = Int32.Parse(childCells[3].InnerText); //statsObj.Points = statsObj.Goals + statsObj.Assists; statsObj.PIM = Int32.Parse(childCells[5].InnerText); statsObj.Hits = Int32.Parse(childCells[6].InnerText); statsObj.Shots = Int32.Parse(childCells[7].InnerText); statsObj.GWG = Int32.Parse(childCells[8].InnerText); statsObj.DefenseRating = decimal.Parse(childCells[9].InnerText); statsObj.PlusMinus = Int32.Parse(childCells[10].InnerText); statsObj.Wins = Int32.Parse(childCells[12].InnerText); statsObj.Loss = Int32.Parse(childCells[13].InnerText); statsObj.OTL = Int32.Parse(childCells[14].InnerText); analytics.DefenseStats.Add(statsObj); } //this.grd_defense.ItemsSource = _defenseStatistics; }
private static async void PlayGame(string[] splittedInput) { var gameId = splittedInput[1]; var x = splittedInput[2]; var y = splittedInput[3]; var httpClient = new HttpClient(); using (httpClient) { httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("GameId", gameId), new KeyValuePair<string, string>("PositionX", x), new KeyValuePair<string, string>("PositionY", y), }); var response = await httpClient.PostAsync("http://localhost:62859/api/Games/play", content); if (!response.IsSuccessStatusCode) { var messageObj = response.Content.ReadAsAsync<ErrorDTO>().Result; Console.WriteLine(messageObj.Message + "; Description: " + messageObj.ExceptionMessage); } else { var gameid = response.Content.ReadAsStringAsync().Result; Console.WriteLine("Game is running, id: " + gameid); } } }
public async Task Authenticate() { var loginRequestData = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("username", _username), new KeyValuePair<string, string>("password", _password) }); var response = await httpClient.PostAsync("/user/login", loginRequestData); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); dynamic jsonData = JsonConvert.DeserializeObject(responseBody); if (jsonData == null) throw new NestException(response); if (jsonData.urls == null) throw new NestException(response); AccessToken = jsonData.access_token; AccessTokenExpiration = jsonData.expires_in; UserId = jsonData.userid; var urls = jsonData.urls; ApiUrl = urls.rubyapi_url; TransportApiBaseAddress = urls.transport_url; WeatherUrl = urls.weather_url; }
public async Task<RegisterDataDTO> RegisterUser(string[] parameters) { const string registrationEndpoint = BaseUrl + RequesterUrlConstants.RegistrationPath; var email = parameters[0]; var password = parameters[1]; var confirmPassword = parameters[2]; var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("email", email), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("confirmPassword", confirmPassword) }); var response = await this.httpClient.PostAsync(registrationEndpoint, content); await this.ValiadteResponse(response); RegisterDataDTO registerData = new RegisterDataDTO { Email = email }; return registerData; }
//Login to the TDAmeritrade system public Boolean login2(String userName, String password) { Boolean hasLoggedinSuccessfully = false; String UrlAuthentication = "https://auth.tdameritrade.com/auth?response_type=code&redirect_uri={URLENCODED REDIRECT URI}&client_id={URLENCODED OAUTH USER ID}"; UrlAuthentication = UrlAuthentication.Replace("{URLENCODED REDIRECT URI}", "http://localhost"); UrlAuthentication = UrlAuthentication.Replace("{URLENCODED OAUTH USER ID}", this.key); System.Net.Http.HttpContent content = null; var isAuth = http.asyncPost(UrlAuthentication, content); String urlAddress = "/apps/300/LogIn?source=" + Uri.EscapeDataString(this.key) + "&version=" + Uri.EscapeDataString(this.version); urlAddress = BaseAddress + urlAddress; System.Net.Http.HttpContent httpContent = new System.Net.Http.FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("userid", userName), new KeyValuePair <string, string>("password", password), new KeyValuePair <string, string>("source", this.key), new KeyValuePair <string, string>("version", this.version) }); var result = http.asyncPost(urlAddress, httpContent); return(hasLoggedinSuccessfully); }
public static string Post(string url, PostBody postBody, int timeout = 5000) { try { Logger.Debug($"Post\t{url}"); using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() }) using (var client = new HttpClient(handler)) { var content = new FormUrlEncodedContent(postBody.Body); var magicCodeName = string.Empty; if (Config.TryGet("MagicCodeType", out magicCodeName)) { var magicCodeValue = Config.TryGet("MagicCodeValue", ""); var magicCodePath = Config.TryGet("MagicCodePath", "/"); var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com"); handler.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain)); } var result = client.PostAsync(url, content).Result; result.EnsureSuccessStatusCode(); return result.Content.ReadAsStringAsync().Result; } } catch (Exception e) { Logger.Error(e.ToString()); return e.Message; } }
public async static Task <SampleJSONService> CallPostAsync() { const string kUrl = "http://jsonplaceholder.typicode.com/posts/"; var postData = new List <KeyValuePair <string, string> >(); postData.Add(new KeyValuePair <string, string>("UserId", "120")); postData.Add(new KeyValuePair <string, string>("Title", "My First Post")); postData.Add(new KeyValuePair <string, string>("Content", "Macoratti .net - Quase tudo para .NET!")); //postData.Add(new KeyValuePair<string, string>("password", userbean.Password)); //postData.Add(new KeyValuePair<string, string>("type", "foods")); //foods, superhero, training, songs var content = new System.Net.Http.FormUrlEncodedContent(postData); var client = new HttpClient(); var response = await client.PostAsync(kUrl, content); //var msg = response.Content.ReadAsStringAsync().Result; //var result = JObject.Parse(msg).ToObject<JSonRest>(); //Debug.WriteLine("Result: " + result.body); //return result; var result = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Result: " + result); return(JObject.Parse(result).ToObject <SampleJSONService>()); }
public async Task<String> PostStringAsync(Uri uri, IDictionary<String, String> content) { using (var http = new HttpClient()) { var formContent = new FormUrlEncodedContent(content); var response = await http.PostAsync(uri, formContent); return await response.Content.ReadAsStringAsync(); } }
public async Task <ICollection <HttpResponseMessage> > SendAsync(PushoverMessage message, params string[] userKeys) { var builder = ImmutableList.CreateBuilder <KeyValuePair <string, string> >(); builder.Add(new KeyValuePair <string, string>("token", _appToken)); builder.AddRange(message.ToKeyValuePairs()); var immutableParameters = builder.ToImmutableList(); var responses = new List <HttpResponseMessage>(); foreach (var userKey in userKeys) { var parameters = immutableParameters.Add(new KeyValuePair <string, string>("user", userKey)); var content = new System.Net.Http.FormUrlEncodedContent(parameters); var response = await HttpHandler.PostAsync(RequestUri, content); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(await response.Content.ReadAsStringAsync()); } responses.Add(response); } return(responses); }
// // GET: /Tasks/ public ActionResult Index() { if (string.IsNullOrEmpty(Request.Params["code"])) { return new RedirectResult("https://accounts.google.com/o/oauth2/auth?" + "response_type=code&client_id=646897896780.apps.googleusercontent.com&" + "redirect_uri=" + HttpUtility.UrlEncode("http://*****:*****@me/lists?alt=json&prettyPrint=true"). Result.Content.ReadAsStreamAsync().Result; var value2 = JsonValue.Load(stream1); return Content((string)value2); } }
public string CreateTag(Tag model, UserData userData) { try { client = new HttpClient(); var postData = new List<KeyValuePair<string, string>>(); postData.Add(new KeyValuePair<string, string>("name", model.name)); HttpContent content = new FormUrlEncodedContent(postData); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.Add("Timestamp", userData.Timestamp.ToString()); content.Headers.Add("Digest", userData.AuthenticationHash); content.Headers.Add("Public-Key", userData.PublicKey); client.PostAsync("http://localhost:3000/tag", content) .ContinueWith(postTask => { postTask.Result.EnsureSuccessStatusCode(); var result = postTask.Result.Content.ReadAsStringAsync(); client.Dispose(); return result; }); } catch (Exception ex) { throw ex; } return null; }
public void PostingCommentOnFriendPostOnNonFriendWallShouldReturn200Ok() { var loginResponse = this.Login(SeededUserUsername, SeededUserPassword); var username = loginResponse.Content.ReadAsStringAsync().Result.ToJson()["userName"]; var user = this.Data.Users.All() .First(u => u.UserName == username); var friendPostOnNonFriendWall = user.Friends .First(fr => fr.UserName == "Jack") .OwnPosts .First(p => p.WallOwner.UserName == "Tanio"); var formData = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("commentContent", "new content") }); int commentCount = friendPostOnNonFriendWall.Comments.Count; var postResponse = this.httpClient.PostAsync( string.Format("api/posts/{0}/comments", friendPostOnNonFriendWall.Id), formData).Result; this.ReloadContext(); Assert.AreEqual(HttpStatusCode.OK, postResponse.StatusCode); Assert.AreEqual(commentCount + 1, this.Data.Posts.GetById(friendPostOnNonFriendWall.Id).Comments.Count); }
public static async Task<bool> SendComment(string username,string userId,string comment) { try { var client = await MalHttpContextProvider.GetHttpContextAsync(); var contentPairs = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("profileMemId", userId), new KeyValuePair<string, string>("commentText", comment), new KeyValuePair<string, string>("profileUsername", username), new KeyValuePair<string, string>("csrf_token", client.Token), new KeyValuePair<string, string>("commentSubmit", "Submit Comment") }; var content = new FormUrlEncodedContent(contentPairs); var response = await client.PostAsync("/addcomment.php", content); return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.SeeOther; } catch (WebException) { MalHttpContextProvider.ErrorMessage("Messages"); return false; } }
public async Task <bool> Create(string newCode) { // App id must have already been set if (Id != null || Code != null) { throw new ArgumentException("The Id has already been set for this object"); } // Update the current code List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >(); parms.Add(new KeyValuePair <string, string>("content", newCode)); parms.Add(new KeyValuePair <string, string>("fromCodeType", "code")); parms.Add(new KeyValuePair <string, string>("create", "Create")); var content = new System.Net.Http.FormUrlEncodedContent(parms); var response = await myConnection.PostAsync(myConnection.CreateDeviceTypeUri, content); if (response.StatusCode != HttpStatusCode.Found) { return(false); } // Dig the Id out of the reponse location string[] segments = response.Headers.Location.Segments; Id = segments[segments.Length - 1]; Code = newCode; // Success return(true); }
async public Task <CookieContainer> getAccountCookie(string mail, string pass) { if (mail == null || pass == null) { return(null); } var loginUrl = "https://secure.nicovideo.jp/secure/login?site=nicolive"; // var param = "mail=" + mail + "&password="******"mail", mail }, { "password", pass } }); var _res = await http.PostAsync(loginUrl, content); var res = await _res.Content.ReadAsStringAsync(); // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; cc = handler.CookieContainer; // return cc; } catch (Exception e) { util.debugWriteLine(e.Message + e.StackTrace + util.getMainSubStr(isSub)); return(null); } var c = cc.GetCookies(TargetUrl)["user_session"]; var secureC = cc.GetCookies(TargetUrl)["user_session_secure"]; cc = copyUserSession(cc, c, secureC); log += (c == null) ? "ユーザーセッションが見つかりませんでした。" : "ユーザーセッションが見つかりました。"; log += (secureC == null) ? "secureユーザーセッションが見つかりませんでした。" : "secureユーザーセッションが見つかりました。"; if (c == null && secureC == null) { return(null); } /* * var encoder = System.Text.Encoding.GetEncoding("UTF=8"); * var sr = new System.IO.StreamReader(resStream, encoder); * var xml = sr.ReadToEnd(); * sr.Close(); * resStream.Close(); * * if (xml.IndexOf("not login") != -1) return null; */ return(cc); }
async public Task <CookieContainer> getAccountCookie(string mail, string pass) { if (mail == null || pass == null) { return(null); } var isNew = true; string loginUrl; Dictionary <string, string> param; if (isNew) { loginUrl = "https://account.nicovideo.jp/login/redirector"; param = new Dictionary <string, string> { { "mail_tel", mail }, { "password", pass }, { "auth_id", "15263781" } //dummy }; } else { loginUrl = "https://secure.nicovideo.jp/secure/login?site=nicolive"; param = new Dictionary <string, string> { { "mail", mail }, { "password", pass } }; } try { var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; var http = new System.Net.Http.HttpClient(handler); var content = new System.Net.Http.FormUrlEncodedContent(param); http.DefaultRequestHeaders.Add("User-Agent", util.userAgent); var _res = await http.PostAsync(loginUrl, content).ConfigureAwait(false); var res = await _res.Content.ReadAsStringAsync().ConfigureAwait(false); // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; var cc = handler.CookieContainer; var c = cc.GetCookies(TargetUrl)["user_session"]; var secureC = cc.GetCookies(TargetUrl)["user_session_secure"]; cc = setUserSession(cc, c, secureC); log += (c == null) ? "ユーザーセッションが見つかりませんでした。" : "ユーザーセッションが見つかりました。"; log += (secureC == null) ? "secureユーザーセッションが見つかりませんでした。" : "secureユーザーセッションが見つかりました。"; if (c == null && secureC == null) { return(null); } return(cc); } catch (Exception e) { util.debugWriteLine(e.Message + e.StackTrace); return(null); } }
async void LoginButton_Clicked(object sender, EventArgs e) { var param = new Dictionary <string, string>(); param.Add("username", usernameEntry.Text); param.Add("password", passwordEntry.Text); var content = new System.Net.Http.FormUrlEncodedContent(param); var client = new HttpClient(); client.BaseAddress = App.BaseAddress; loginButton.IsEnabled = false; usernameEntry.IsEnabled = false; passwordEntry.IsEnabled = false; indicator.IsVisible = true; var response = await client.PostAsync("api/MemberAuthen", content); loginButton.IsEnabled = true; usernameEntry.IsEnabled = true; passwordEntry.IsEnabled = true; indicator.IsVisible = false; // if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { await DisplayAlert("Warning", "User or Password incorrect", "OK"); return; } if (response.StatusCode != System.Net.HttpStatusCode.OK) { return; } var json = await response.Content.ReadAsStringAsync(); var member = JObject.Parse(json).ToObject <Member>(); Helpers.Settings.IsLoggedIn = true; Helpers.Settings.MemberId = member.Id; Helpers.Settings.Fullname = member.Fullname; Helpers.Settings.Picture = member.FacebookPicture; //change page no bck to login -- mainpage var app = Parent as App; var mp = new MasterDetailPage(); mp.Master = new MenuPage(); mp.Detail = new NavigationPage(new MainPage()); app.MainPage = mp; }
public List <StatsTeam> GetTeams() { var cookies = new CookieContainer(); Login(cookies); string teamHtml; List <StatsTeam> statsTeams = new List <StatsTeam>(); foreach (var seasonId in SeasonStatsToPull) { using (var httpClient = new HttpClient()) { var values = new Dictionary <string, string> { { "season", seasonId.ToString() }, { "stage", "1" }, { "button", "view+season" } }; var content = new System.Net.Http.FormUrlEncodedContent(values); var response = httpClient.PostAsync("http://xbox-sports.com/leagues/xbshl/index.php?mode=standings", content).GetAwaiter().GetResult(); teamHtml = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); } var teamDoc = new HtmlDocument(); teamDoc.LoadHtml(teamHtml); var teamTable = teamDoc.DocumentNode.Descendants().Single(x => x.HasClass("table_1") && x.Id == "sort_table"); var statRows = teamTable.ChildNodes[3].ChildNodes.Where(x => x.Name == "tr"); foreach (var statRow in statRows) { var cells = statRow.ChildNodes.Where(x => x.Name == "td").ToArray(); statsTeams.Add(new StatsTeam() { TeamAbbreviation = TeamNameHelper.GetTeamAbbreviation(cells[0].ChildNodes[1].InnerText), TeamName = cells[0].ChildNodes[1].InnerText, GamesPlayed = Int32.Parse(cells[1].InnerText.Replace(",", "")), Wins = Int32.Parse(cells[2].InnerText.Replace(",", "")), Loss = Int32.Parse(cells[3].InnerText.Replace(",", "")), OTL = Int32.Parse(cells[4].InnerText.Replace(",", "")), Points = Int32.Parse(cells[5].InnerText.Replace(",", "")), GoalsFor = Int32.Parse(cells[7].InnerText.Replace(",", "")), GoalsAgainst = Int32.Parse(cells[8].InnerText.Replace(",", "")), Hits = Int32.Parse(cells[9].InnerText.Replace(",", "")), Shots = Int32.Parse(cells[10].InnerText.Replace(",", "")), PIM = Int32.Parse(cells[11].InnerText.Replace(",", "")), Season = seasonId }); } } return(statsTeams); }
public static string SendHttpRequest(string url, List <KeyValuePair <String, String> > paramList, string contentType = "application/x-www-form-urlencoded") { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); System.Net.Http.FormUrlEncodedContent content = new System.Net.Http.FormUrlEncodedContent(paramList); content.Headers.ContentType.MediaType = contentType; System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(new Uri(url), content).Result; string res = response.Content.ReadAsStringAsync().Result; return(res); }
public async Task <bool> EnableOauth() { // App id must have already been set if (Id == null) { throw new ArgumentException("The Id must be set before oauth can be enabled"); } // Find all the installed smart apps clientKey = await myConnection.GetStringAsync(myConnection.GetUuidUri); secretKey = await myConnection.GetStringAsync(myConnection.GetUuidUri); // Dig these out of the code code otherwise the oauth update will fail! string name = FindVarInSrc("name"); string @namespace = FindVarInSrc("namespace"); string author = FindVarInSrc("author"); string description = FindVarInSrc("description"); string iconUrl = FindVarInSrc("iconUrl"); string iconX2Url = FindVarInSrc("iconX2Url"); string iconX3Url = FindVarInSrc("iconX3Url"); // Enable Oauth on the smart app List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >(); parms.Add(new KeyValuePair <string, string>("id", Id)); parms.Add(new KeyValuePair <string, string>("name", name)); parms.Add(new KeyValuePair <string, string>("namespace", @namespace)); parms.Add(new KeyValuePair <string, string>("author", author)); parms.Add(new KeyValuePair <string, string>("description", description)); parms.Add(new KeyValuePair <string, string>("gitRepo.id", "")); parms.Add(new KeyValuePair <string, string>("_isShared", "")); parms.Add(new KeyValuePair <string, string>("iconUrl", iconUrl)); parms.Add(new KeyValuePair <string, string>("iconX2Url", iconX2Url)); parms.Add(new KeyValuePair <string, string>("iconX3Url", iconX3Url)); parms.Add(new KeyValuePair <string, string>("clientId", clientKey)); parms.Add(new KeyValuePair <string, string>("clientSecret", secretKey)); parms.Add(new KeyValuePair <string, string>("displayName", name)); parms.Add(new KeyValuePair <string, string>("displayLink", "")); parms.Add(new KeyValuePair <string, string>("photoUrls", "")); parms.Add(new KeyValuePair <string, string>("videoUrls.0.videoUrl", "")); parms.Add(new KeyValuePair <string, string>("videoUrls.0.thumbnailUrl", "")); parms.Add(new KeyValuePair <string, string>("update", "Update")); var content = new System.Net.Http.FormUrlEncodedContent(parms); var response = await myConnection.PostAsync(myConnection.UpdateSmartAppUri, content); if (response.StatusCode != HttpStatusCode.Found) { throw new Exception($"Oauth could not be enabled. Status code {response.StatusCode}"); } return(true); }
async void SendLocationToServer(TimeTable currentTimeTable) { try { if (IsLocationAvailable()) { var position = await CrossGeolocator.Current.GetPositionAsync(timeout : TimeSpan.FromSeconds(10)); Debug.WriteLine(string.Format("Location: {0:0.0000}, {1:0.0000}", position.Latitude, position.Longitude), "Chaopraya Boat"); var param = new Dictionary <string, string>(); param.Add("latitude", position.Latitude.ToString()); param.Add("longitude", position.Longitude.ToString()); param.Add("timetableid", currentTimeTable.Id.ToString()); var content = new System.Net.Http.FormUrlEncodedContent(param); var client = new HttpClient(); client.BaseAddress = App.BaseAddress; var response = await client.PostAsync("api/AddBoatLocation", content); // if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = await response.Content.ReadAsStringAsync(); var isActive = bool.Parse(result); currentTimeTable.IsActive = isActive; if (!isActive) { timetableListViewq.ItemsSource = timeTables.Where(x => x.IsActive).ToList(); } } } } catch (Exception ex) { await DisplayAlert("Error", ex.Message, "OK"); } //await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 10, true, new Plugin.Geolocator.Abstractions.ListenerSettings //{ // ActivityType = Plugin.Geolocator.Abstractions.ActivityType.AutomotiveNavigation, // AllowBackgroundUpdates = true, // DeferLocationUpdates = true, // DeferralDistanceMeters = 1, // DeferralTime = TimeSpan.FromSeconds(1), // ListenForSignificantChanges = true, // PauseLocationUpdatesAutomatically = false //}); //CrossGeolocator.Current.PositionChanged += Current_PositionChanged; }
/// <summary> /// サーバーにデータを送信するメソッド。 /// </summary> /// <param name="post">送信される文字列</param> /// <returns>サーバーから返ってきた値。</returns> private async Task <string> OnlinePost(string post) { Dictionary <string, string> data = new Dictionary <string, string> { { KEY_NAME, post }, }; var content = new System.Net.Http.FormUrlEncodedContent(data); var response = await client.PostAsync(this.SERVER_URL, content); return(await response.Content.ReadAsStringAsync()); }
internal async void CheckTaskAsync(Model.Task item) { item.Checked = !item.Checked; var values = new Dictionary <string, string> { { "TravelId", Travel.id.ToString() }, { "TaskId", item.Id.ToString() }, { "Completed", item.Checked.ToString() }, }; var content = new System.Net.Http.FormUrlEncodedContent(values); var result = await Client.HttpClient.PutAsync("http://localhost:65177/api/Travel/Task", content); }
/// <summary> /// オンラインに非同期でセーブコマンドを送信するメソッド /// </summary> /// <param name="data">RankigData型:送信するランキングデータ</param> /// <returns>実行したSQLコマンド, もしくはサーバーから返信されたエラーメッセージ</returns> private async Task <string> SendOnlineSaveData(RankingData data) { var content = new System.Net.Http.FormUrlEncodedContent(data.Dictionary()); var client = new System.Net.Http.HttpClient(); Log.Info("【Online】Access to server."); Log.Info($"【Online】Address is [{BaseUrl}{SAVE_DATA_URL}]."); Log.Info($"【Online】【Transmission】Ranking Data [{data.ToString()}]."); Log.Info($"【Online】【Transmission】Contents [{ content.ToString()}]."); var response = await client.PostAsync(BaseUrl + SAVE_DATA_URL, content); return(await response.Content.ReadAsStringAsync()); }
async void LoginButton_Clicked(object sender, EventArgs e) { var param = new Dictionary <string, string>(); param.Add("username", usernameEntry.Text); param.Add("password", passwordEntry.Text); var content = new System.Net.Http.FormUrlEncodedContent(param); var client = new HttpClient(); client.BaseAddress = App.BaseAddress; loginButton.IsEnabled = false; usernameEntry.IsEnabled = false; passwordEntry.IsEnabled = false; indicator.IsVisible = true; var response = await client.PostAsync("api/DriverAuthen", content); loginButton.IsEnabled = true; usernameEntry.IsEnabled = true; passwordEntry.IsEnabled = true; indicator.IsVisible = false; // if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { await DisplayAlert("Warning", "User or Password incorrect", "OK"); return; } if (response.StatusCode == System.Net.HttpStatusCode.NoContent) { await DisplayAlert("Warning", "No time table", "OK"); return; } if (response.StatusCode != System.Net.HttpStatusCode.OK) { return; } var json = await response.Content.ReadAsStringAsync(); var timetables = JArray.Parse(json).ToObject <List <TimeTable> >(); await Navigation.PushModalAsync(new KeepCoordinatePage(timetables)); }
public static HttpWebRequest SetRequestObjWithFormUrlEncoded <T>(this HttpWebRequest req, T obj) { req.SetMethod(HttpMethod.Post); req.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; req.KeepAlive = false; using (var writer = new StreamWriter(req.GetRequestStream())) { var param = obj.GetType().GetProperties().Select(x => new KeyValuePair <string, string>(x.Name, x.GetValue(obj)?.ToString())); var str = new System.Net.Http.FormUrlEncodedContent(param).ReadAsStringAsync().GetAwaiter().GetResult(); writer.Write(str); } return(req); }
public static string SendHttpRequest(string url) { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >(); paramList.Add(new KeyValuePair <string, string>("scope", "data:read data:write")); paramList.Add(new KeyValuePair <string, string>("client_secret", "C4fe9fe9df9cc47c")); paramList.Add(new KeyValuePair <string, string>("grant_type", "client_credentials")); paramList.Add(new KeyValuePair <string, string>("client_id", "sWSQ59iBg1FQqLvLRcYwNEyuCBomL3xj")); System.Net.Http.FormUrlEncodedContent content = new System.Net.Http.FormUrlEncodedContent(paramList); content.Headers.ContentType.MediaType = "application/x-www-form-urlencoded"; System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(new Uri(url), content).Result; string res = response.Content.ReadAsStringAsync().Result; return(res); }
public static byte[] PostUrlEncodeBodyReturnBytes(string url, IDictionary <string, string> values, Encoding encoding = null, IDictionary <string, string> headers = null, string referrer = null, string accept = null) { var client = SetupClient(headers, referrer, accept); var content = new System.Net.Http.FormUrlEncodedContent(values); content.Headers.ContentType.CharSet = (encoding ?? Encoding.UTF8).BodyName; content.Headers.ContentType.MediaType = "application/x-www-form-urlencoded"; var ret = client.PostAsync(url, content).Result; if (ret.IsSuccessStatusCode == false) { throw new Exception("HTTP请求错误:" + ret.StatusCode); } var data = ret.Content.ReadAsByteArrayAsync().Result; return(data); }
private Task <HttpResponseMessage> ExecuteDelete(string url, string apikey = "") { var client = new HttpClient(); var content = new System.Net.Http.FormUrlEncodedContent(null); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded"); if (!string.IsNullOrEmpty(apikey)) { //var byteArray = Encoding.UTF8.GetBytes(apikey); //client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(" ", apikey); client.DefaultRequestHeaders.Add("Autenticate", apikey); } client.BaseAddress = new Uri(ConnectionHelper.AppUrl); return(client.DeleteAsync(url)); }
private async Task <OAuth2Token> RequestToken_AuthorizationCodeGrant(HttpClient client, HttpRequestMessage request) { using (var creds = await _Settings.ClientCredentialProvider.GetCredentials().ConfigureAwait(false)) { var authCodeUrlBuilder = new UriBuilder(_Settings.AuthorizeUrl); string state = _Settings?.State?.Invoke(request); authCodeUrlBuilder.Query = $"client_id={Uri.EscapeDataString(creds.Identifier)}&redirect_uri={Uri.EscapeDataString(_Settings.RedirectUrl.ToString())}&response_type=code&scope={Uri.EscapeDataString(_Settings.Scope)}"; if (!String.IsNullOrEmpty(state)) { authCodeUrlBuilder.Query += "&state=" + Uri.EscapeDataString(state); } var authCodeResult = await _Settings.RequestAuthentication(authCodeUrlBuilder.Uri).ConfigureAwait(false); if (authCodeResult == null || String.IsNullOrWhiteSpace(authCodeResult.AuthorisationCode)) { throw new UnauthorizedAccessException(authCodeResult.ErrorResponse ?? "No authorisation code returned."); } if (authCodeResult.State != state) { throw new UnauthorizedAccessException("Unexpected 'state' value returned from authentication url."); } var values = new Dictionary <string, string>(7); values.Add("grant_type", OAuth2GrantTypes.AuthorizationCode); values.Add("client_id", creds.Identifier); values.Add("client_secret", creds.Secret); values.Add("redirect_uri", _Settings.RedirectUrl.ToString()); values.Add("scope", _Settings.Scope); values.Add("code", authCodeResult.AuthorisationCode); if (!String.IsNullOrEmpty(authCodeResult.State)) { values.Add("state", authCodeResult.AuthorisationCode); } var content = new System.Net.Http.FormUrlEncodedContent(values); var tokenResult = await client.PostAsync(_Settings.AccessTokenUrl, content).ConfigureAwait(false); return(await ProcessTokenResponse(tokenResult).ConfigureAwait(false)); } }
public async Task <bool> Login(string user, string password) { List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >(); parms.Add(new KeyValuePair <string, string>("j_username", user)); parms.Add(new KeyValuePair <string, string>("j_password", password)); var content = new System.Net.Http.FormUrlEncodedContent(parms); var response = await PostAsync(LoginUrl, content); if (response.StatusCode != HttpStatusCode.Redirect || response.Headers.Location?.ToString().Contains("authfail") == true) { return(false); } // Success IsLoggedIn = true; return(true); }
/// <summary> /// Posts a message back to the browser, via App Engine. /// </summary> /// <param name="postStatusUrl">Where to post the status to?</param> /// <param name="postStatusToken">An additional value to post.</param> /// <param name="status">The status to report to the browser.</param> /// <param name="result">The result or error message to report to the browser.</param> private void PublishStatus(string postStatusUrl, string postStatusToken, string status, string result = null) { var content = new System.Net.Http.FormUrlEncodedContent( new Dictionary <string, string>() { { "status", status }, { "token", postStatusToken }, { "result", result }, { "host", System.Environment.MachineName } }); var httpPost = _init.HttpClient.PostAsync(postStatusUrl, content); httpPost.Wait(); if (httpPost.Result.StatusCode != System.Net.HttpStatusCode.OK) { throw new FatalException(httpPost.Result.ToString()); } }
public void Register(string username) { try { client = new HttpClient(); var postData = new List<KeyValuePair<string, string>>(); postData.Add(new KeyValuePair<string, string>("email", username)); HttpContent content = new FormUrlEncodedContent(postData); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); client.PostAsync("http://localhost:3000/User", content) .ContinueWith(postTask => { postTask.Result.EnsureSuccessStatusCode(); client.Dispose(); }); } catch (Exception ex) { } }
public async Task MashapeFacebookLogin() { //NOTE: Check App.xaml.cs for the variables that you need to fill in var targeturi = "https://ismaelc-facebooktest.p.mashape.com/oauth_url"; var client = new System.Net.Http.HttpClient(); HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("consumerKey", App.ConsumerKey), new KeyValuePair<string, string>("consumerSecret", App.ConsumerSecret), new KeyValuePair<string, string>("callbackUrl", App.CallbackUrl) }); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.Add("X-Mashape-Authorization", App.MashapeHeader); progressRing.IsActive = true; btnLogin.IsEnabled = false; var response = await client.PostAsync(targeturi, content); progressRing.IsActive = false; btnLogin.IsEnabled = true; if (response.IsSuccessStatusCode) { string respContent = await response.Content.ReadAsStringAsync(); string loginUrl = await Task.Run(() => JsonObject.Parse(respContent).GetNamedString("url")); WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(loginUrl), new Uri(App.CallbackUrl)); if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { btnLogin.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var callBackUrl = WebAuthenticationResult.ResponseData.ToString(); //Where's ParseQueryString when you need it... App.AccessToken = GetParameter(callBackUrl, "accessToken"); //App.AccessSecret = GetParameter(callBackUrl, "accessSecret"); } else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { throw new InvalidOperationException("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString()); } else { // The user canceled the authentication } } else { //The POST failed, so update the UI accordingly //txtBlockResult.Text = "Error"; } }