/// <summary> /// Gets the Xml as a string from the URL provided /// </summary> /// <returns>The server info XML as a string</returns> private async Task GetXml() { HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); IEnumerable<Certificate> certificates = await CertificateStores.FindAllAsync(new CertificateQuery { FriendlyName = "Limelight-Client" }); filter.ClientCertificate = certificates.Single(); client = new Windows.Web.Http.HttpClient(filter); Debug.WriteLine(uri); if (rawXmlString == null) { try { rawXmlString = await client.GetStringAsync(uri); } catch (Exception e) { Debug.WriteLine(e.Message); } Debug.WriteLine(rawXmlString); // Up to the caller to deal with exceptions resulting here this.rawXml = XDocument.Parse(rawXmlString); } }
private async Task<String> SendDataAsync(String Url) { try { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); return await httpClient.GetStringAsync(new Uri(Url)); } catch (Exception Err) { //rootpage.NotifyUser("Error getting data from server." + Err.Message, NotifyType.StatusMessage); } return null; }
/// <summary> /// Gets the Xml as a string from the URL provided /// </summary> /// <returns>The server info XML as a string</returns> private async Task GetXml() { // Return if we've already been here if (ranQuery) { return; } else { ranQuery = true; } HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); // Allow the crypto provider to generate the cert if needed await new WindowsCryptoProvider().InitializeCryptoProviderKeys(); IEnumerable<Certificate> certificates = await CertificateStores.FindAllAsync(new CertificateQuery { FriendlyName = "Limelight-Client" }); filter.ClientCertificate = certificates.Single(); client = new Windows.Web.Http.HttpClient(filter); Debug.WriteLine(uri); try { rawXmlString = await client.GetStringAsync(uri); } catch (Exception e) { Debug.WriteLine(e.Message); return; } Debug.WriteLine(rawXmlString); // Up to the caller to deal with exceptions resulting here this.rawXml = XDocument.Parse(rawXmlString); }
public async Task <String> AuthenticateUser(string email, string password) { string json = JsonConvert.SerializeObject(new { email = email, password = password }); HttpClient httpClient = new HttpClient(); try { var res = await httpClient.PostAsync(new Uri("http://localhost:5001/api/Account"), new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); String access_token = res.Content.ToString(); if (access_token == null) { throw new Exception(); } return(access_token); } catch (Exception) { MessageDialog md = new MessageDialog("Error authenticating"); await md.ShowAsync(); return(null); } }
public async Task <string> postFile(StorageFile file) { var httpClient = new Windows.Web.Http.HttpClient(); var formContent = new HttpMultipartFormDataContent(); var fileContent = new HttpStreamContent(await file.OpenReadAsync()); fileContent.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("mp3"); var apiKeyContent = new HttpStringContent(APIKEY); var apiSecretContent = new HttpStringContent(APISECRET); var cloudNameContent = new HttpStringContent(CLOUDNAME); formContent.Add(fileContent, "myFile", file.Name); formContent.Add(apiKeyContent, "apiKey"); formContent.Add(apiSecretContent, "apiSecret"); formContent.Add(cloudNameContent, "cloudName"); var response = await httpClient.PostAsync(new Uri(APIPOSTFILE), formContent); var stringContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine(stringContent); string url = JObject.Parse(stringContent)["url"].ToString(); if (url.Length > 0) { return(url); } return(""); }
/// <summary> /// Load the Settings from the backend. /// </summary> /// <returns>Returns a JSON formated string.</returns> public async Task <string> LoadSettings() { try { Logger.Trace("LoadSettings"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(string.Format(Configuration.SettingsUri, Configuration.ApiKey)); HttpClient httpClient = new HttpClient(baseProtocolFilter); var responseMessage = await httpClient.SendRequestAsync(requestMessage); Logger.Trace("LoadSettings HTTPCode: {0}", responseMessage.StatusCode); LastCallResult = responseMessage.IsSuccessStatusCode ? NetworkResult.Success : NetworkResult.UnknownError; return(responseMessage?.Content.ToString()); } catch (Exception ex) { Logger.Error("LoadSettings Error", ex); LastCallResult = NetworkResult.NetworkError; return(null); } }
private async void programO(string Input, bool key) { string url = "http://api.program-o.com/v2/chatbot/"; var deviceInformation = new EasClientDeviceInformation(); string Id = deviceInformation.Id.ToString(); if (Input == "" || Input.Replace(" ", "") == "") { if (key == false) { Input = "Hi!"; txtOutputTwo.Text = Input; } else { Input = "Hi!"; } } else { txtOutputTwo.Text = Input; } string param = "?bot_id=6&convo_id=sam" + Id.Substring(0, 12) + "&format=json&say=" + Input; // Send Request Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Uri requestUri = new Uri(url + param); Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); JsonObject root = JsonValue.Parse(httpResponseBody).GetObject(); string text = Convert.ToString(root["botsay"]); txtOutput.Text = ((text.Replace("\"", "")).Replace("Program-O", "Sam")).Replace("\\", ""); } catch { Random r = new Random(); int nr = r.Next(1, 3); if (nr == 1) { txtOutput.Text = "Check your internet connection!"; } else { txtOutput.Text = "Error can't connect to my ship!"; } } txtInput.Text = ""; }
/// <summary> /// 发送GET请求 返回服务器回复数据(string) /// </summary> /// <param name="url"></param> /// <returns></returns> public async static Task<string> SendGetRequestAsync(string url) { try { HttpClient client = new HttpClient(); Uri uri = new Uri(url); HttpResponseMessage response = await client.GetAsync(uri).AsTask(Cts.Token); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync().AsTask(Cts.Token); } //catch (TaskCanceledException) //{ //} catch (Exception) { return null; } //if (Cts.Token.CanBeCanceled) //{ // Cts.Cancel(); //} // await Dispatcher }
public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); // ShowToast("Hello", true); // Windows.Web.Http.HttpClient clt = new Windows.Web.Http.HttpClient(); // response = await clt.GetStringAsync(new Uri("http://158.69.222.199/inder.php?" + DateTime.Now)); var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Dictionary <string, string> pairs = new Dictionary <string, string>(); pairs.Add("id", localSettings.Values["id"].ToString()); pairs.Add("pos", localSettings.Values["Position"].ToString()); HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs); Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(); //Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(new Uri("http://localhost/chkpos.php?" + DateTime.Now), formContent); Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(new Uri("http://158.69.222.199/chkpos.php?" + DateTime.Now), formContent); //response = await clt.GetStringAsync(new Uri("http://localhost/inder.php?" + DateTime.Now)); if (response.Content.ToString().Equals("change")) { ShowToast("Please change the position.", true); } else if (response.Content.ToString().Equals("nchange")) { ShowToast("Dont change the position.", true); } deferral.Complete(); }
public static async Task <string> sendDataToServer(string aUrl, string json) { string result = ""; var httpClient = new HttpClient(); // Always catch network exceptions for async methods try { httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpRequestMessage msg = new Windows.Web.Http.HttpRequestMessage(new Windows.Web.Http.HttpMethod("POST"), new Uri(aUrl)); msg.Content = new HttpStringContent((json)); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); var response = await httpClient.SendRequestAsync(msg).AsTask(); var statusCode = response.StatusCode; if (statusCode == HttpStatusCode.Ok) { result = await response.Content.ReadAsStringAsync(); } } catch { // Details in ex.Message and ex.HResult. } // Once your app is done using the HttpClient object call dispose to // free up system resources (the underlying socket and memory used for the object) httpClient.Dispose(); return(result); }
public async System.Threading.Tasks.Task RemoveItem(Item item) { var itemIdJson = JsonConvert.SerializeObject(item.Id); HttpClient httpClient = new HttpClient(); var url = $"http://localhost:5001/api/Category/DeleteItem/{item.Id}"; var res = await httpClient.DeleteAsync(new Uri(url)); if (res.IsSuccessStatusCode) { Category cat = null; foreach (Category c in Categories) { if (c.Items.Contains(item)) { cat = c; } } if (cat != null) { cat.Items.Remove(item); Category tCat = Travellist.Categories.SingleOrDefault(c => c.Id == cat.Id); tCat.Items.Remove(item); } } }
public async Task <string> GetGardenTeacher(string email, string type) { string completeUri = "http://childappapiservice.azurewebsites.net/api/users?email=" + email + "&type=" + type; Uri requestUri = new Uri(completeUri); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); user getUser = ReadToObjectUser(httpResponseBody); return(getUser.email); } catch (Exception ex) { return(""); } }
public static async Task <HtmlDocument> GetHtmlDoc(string relativeUri) { //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); HttpRequestMessage HttpRequestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(DataSource.requestUri, relativeUri)); HttpRequestMessage.Headers.Add("User-Agent", DataSource.CustomUserAgent); try { //Send the GET request httpResponse = await httpClient.SendRequestAsync(HttpRequestMessage); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(httpResponseBody); return(htmlDoc); }
private async Task <int?> PostToWns(string uri, string AccessToken, string xml, string notificationType, string contentType) { try { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Uri requestUri = new Uri(uri); HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), requestUri); msg.Content = new HttpStringContent(CreateXMLtemplet(xml)); msg.Headers.Add("X-WNS-Type", notificationType); msg.Headers.Add("Authorization", String.Format("Bearer {0}", AccessToken)); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("text/xml"); HttpResponseMessage HttpResponseMessage = await httpClient.SendRequestAsync(msg).AsTask(); if (HttpResponseMessage.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { var resultsss = await HttpResponseMessage.Content.ReadAsStringAsync(); return(await Task.FromResult(1)); } else { return(await Task.FromResult(0)); } } catch (Exception ex) { return(await Task.FromResult(0)); } }
/// <summary> /// Moves needed cookies to globaly used client by WebViews control, web view authentication in other words. /// </summary> /// <returns></returns> public static async Task InitializeContextForWebViews(bool mobile) { if (_webViewsInitialized) return; _webViewsInitialized = true; var filter = new HttpBaseProtocolFilter(); var httpContext = await MalHttpContextProvider.GetHttpContextAsync(); var cookies = httpContext.Handler.CookieContainer.GetCookies(new Uri(MalHttpContextProvider.MalBaseUrl)); if (mobile) { filter.CookieManager.SetCookie(new HttpCookie("view", "myanimelist.net", "/") { Value = "sp" }); } foreach (var cookie in cookies.Cast<Cookie>()) { try { var newCookie = new HttpCookie(cookie.Name, cookie.Domain, cookie.Path) { Value = cookie.Value }; filter.CookieManager.SetCookie(newCookie); } catch (Exception) { var msg = new MessageDialog( "Authorization failed while rewriting cookies, I don't know why this is happenning and after hours of debugging it fixed itself after reinstall. :(","Something went wrong™"); await msg.ShowAsync(); } } filter.AllowAutoRedirect = true; Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(filter); //use globaly by webviews }
public async Task <String> RegisterUser(string email, string password, string confirmPassword, string firstname, string lastname) { string json = JsonConvert.SerializeObject(new { email = email, password = password, firstname = firstname, lastname = lastname, passwordConfirmation = confirmPassword }); HttpClient httpClient = new HttpClient(); try { var res = await httpClient.PostAsync(new Uri("http://localhost:5001/api/Account/register"), new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); String access_token = res.Content.ToString(); if (access_token == null) { throw new Exception(); } return(access_token); } catch (Exception) { return(null); } }
public async Task <StorageFile> GetFileAsync() { try { var httpClient = new Windows.Web.Http.HttpClient(); var buffer = await httpClient.GetBufferAsync(new Uri("http://www.neu.edu.cn/indexsource/neusong.mp3")); if (buffer != null) { StorageFile File = await KnownFolders.MusicLibrary.CreateFileAsync( "neusong.mp3", CreationCollisionOption.ReplaceExisting); using (var stream = await File.OpenAsync(FileAccessMode.ReadWrite)) { await stream.WriteAsync(buffer); await stream.FlushAsync(); } // var stream = await File.OpenAsync(FileAccessMode.ReadWrite); // await stream.WriteAsync(buffer); //await stream.FlushAsync(); MyText.Text = "neusong"; return(File); } } catch { } return(null); }
public async Task <string> GetParentContactAsync(string email) { string completeUri = "http://childappapiservice.azurewebsites.net/api/contacts?Parentemail=" + email + "&isParent=true"; Uri requestUri = new Uri(completeUri); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); string childEmail = JsonConvert.DeserializeObject <string>(httpResponseBody); return(childEmail); } catch (Exception ex) { return(null); } }
private async Task <int?> GetAccessToken() { OAuthToken oAuthToken = new OAuthToken(); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var urlEncodedSecret = System.Net.WebUtility.UrlEncode(secret); var urlEncodedSid = System.Net.WebUtility.UrlEncode(sid); var body = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret); Uri requestUri = new Uri("https://login.live.com/accesstoken.srf"); HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), requestUri); msg.Content = new HttpStringContent(body); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage HttpResponseMessage = await httpClient.SendRequestAsync(msg).AsTask(); if (HttpResponseMessage.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { var resultsss = await HttpResponseMessage.Content.ReadAsStringAsync(); oAuthToken = GetOAuthTokenFromJson(resultsss); currentOAuthToken = oAuthToken.AccessToken; } return(await Task.FromResult(1)); }
public async void updateIp(object state) { await Window.Current.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { statusTb.Text = "Updating Local IP..."; }); var getip = new Windows.Web.Http.HttpClient(); var htmlbody = await getip.GetStringAsync(new Uri("http://checkip.dyndns.org/")); var substring = htmlbody.ToString().Replace("<html><head><title>Current IP Check</title></head><body>Current IP Address: ", ""); var internetip = substring.ToString().Replace("</body></html>\r\n", ""); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue( "Basic", Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes( string.Format("{0}:{1}", "kesava", "95123456")))); var resp = await client.GetAsync(new Uri("http://dynupdate.no-ip.com/nic/update?hostname=kesava89.ddns.net&myip=" + internetip)); var respType = resp.EnsureSuccessStatusCode(); if (respType.IsSuccessStatusCode) { await Window.Current.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { statusTb.Text = "Updating Local IP complete."; }); } else { await Window.Current.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { statusTb.Text = "Please check your internet connection or contact admin. Code: " + respType.StatusCode; }); } }
private static async Task<ChatResult> GetChatsDataAsync(string searchTerm = "") { var chatResult = new ChatResult(); var chat = new ObservableCollection<Chat>(); using (var httpClient = new Windows.Web.Http.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 criteria = new LocationListCriteria { // SearchTerm = searchTerm //}; var url = apiUrl + "/api/chat"; //+ JsonConvert.SerializeObject(criteria); using (var httpResponse = await httpClient.GetAsync(new Uri(url))) { string json = await httpResponse.Content.ReadAsStringAsync(); json = json.Replace("<br>", Environment.NewLine); chatResult = JsonConvert.DeserializeObject<ChatResult>(json); } } catch (Exception e) { } } return chatResult; }
public async static Task<bool> SendMessage(string body) { // Namespace info. //var serviceNamespace = "sudhesh"; //var hubName = "test"; //var deviceName = "tisensortag"; //var sharedAccessPolicyName = "all"; //var sharedAccessKey = "ZcfdxuLADoYv3zQycbpddoelgBvogPxnqM7/dfMdU2k="; var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceNamespace, hubName, deviceName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceNamespace, hubName, deviceName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(body) }; //request.Headers.Add("Authorization", sas); //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var nowait = await webClient.SendRequestAsync(request); return nowait.IsSuccessStatusCode; }
public static async Task<Profile> GetProfile() { var profile = new Profile(); using (var httpClient = new Windows.Web.Http.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/profiles"; var httpResponse = await httpClient.GetAsync(new Uri(url)); string json = await httpResponse.Content.ReadAsStringAsync(); json = json.Replace("<br>", Environment.NewLine); profile = JsonConvert.DeserializeObject<Profile>(json); } catch (Exception e) { } } return profile; }
public async Task <user[]> GetGardenChildren(string garden) { string completeUri = "http://childappapiservice.azurewebsites.net/api/users?garden=" + garden; Uri requestUri = new Uri(completeUri); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); user[] gardenUsers = JsonConvert.DeserializeObject <user[]>(httpResponseBody); return(gardenUsers); } catch (Exception ex) { return(null); } }
public async Task<bool> SendMessage(string body) { var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceNamespace, hubName, deviceName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceNamespace, hubName, deviceName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); // webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/json;type=entry;charset=utf-8"); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(body) }; //request.Headers.Add("Authorization", sas); //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var nowait = await webClient.SendRequestAsync(request); // Debug.WriteLine("Success/Error msg: {0}", nowait.StatusCode); return nowait.IsSuccessStatusCode; }
private async Task <string> OnSetCookieRequestAsync(Cookie cookie) { if (Control == null || Element == null) { return(string.Empty); } var url = new Uri(Element.Source); var newCookie = new HttpCookie(cookie.Name, cookie.Domain, cookie.Path); newCookie.Value = cookie.Value; newCookie.HttpOnly = cookie.HttpOnly; newCookie.Secure = cookie.Secure; newCookie.Expires = cookie.Expires; List <HttpCookie> cookieCollection = new List <HttpCookie>(); HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); HttpClient httpClient; filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired); foreach (HttpCookie knownCookie in cookieCollection) { filter.CookieManager.SetCookie(knownCookie); } filter.CookieManager.SetCookie(newCookie); httpClient = new HttpClient(filter); return(await OnGetCookieRequestAsync(cookie.Name)); }
public async void LoginOut() { init(); thedata.DataToOut(); thedata.TransferDataToLoginOut(); string url = "http://w.dlut.edu.cn/cgi-bin/srun_portal"; //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //request.Method = "POST"; //request.ContentType = "application/x-www-form-urlencoded"; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); HttpBufferContent buffer = new HttpBufferContent(thedata.OutData.AsBuffer()); Windows.Web.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), buffer).AsTask(cts.Token); Result = await response.Content.ReadAsStringAsync().AsTask(cts.Token); if (Result.IndexOf("成功") >= 0) { loginresponse = "注销成功"; } else if (Result.IndexOf("失败") >= 0) { loginresponse = "注销失败"; } else { loginresponse = "请检查网络"; } MessageDialog message = new MessageDialog(loginresponse); await message.ShowAsync(); }
public static async Task <string> LoginSucess(string access_token) { Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient(); access_key = access_token; Windows.Web.Http.HttpResponseMessage hr2 = await hc.GetAsync(new Uri("http://api.bilibili.com/login/sso?&access_key=" + access_token + "&appkey=422fd9d7289a1dd9&platform=wp")); hr2.EnsureSuccessStatusCode(); SettingHelper.Set_Access_key(access_token); //看看存不存在Cookie HttpBaseProtocolFilter hb = new HttpBaseProtocolFilter(); HttpCookieCollection cookieCollection = hb.CookieManager.GetCookies(new Uri("http://bilibili.com/")); List <string> ls = new List <string>(); foreach (HttpCookie item in cookieCollection) { ls.Add(item.Name); } if (ls.Contains("DedeUserID")) { if (Logined != null) { Logined(null, null); } return("登录成功"); } else { return("登录失败"); } }
public static async Task <bool> Isfavourite(int imgid, string username, string userpass, string host) { bool isfavourite = false; try { string request = $"login={username}&password_hash={userpass}&id={imgid }"; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var requestMessage = new Windows.Web.Http.HttpRequestMessage(new Windows.Web.Http.HttpMethod("POST"), new Uri($"{host}post/vote.xml")) { Content = new HttpStringContent(request) }; requestMessage.Headers["Accept-Encoding"] = "gzip, deflate, br"; requestMessage.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); var res = await httpClient.SendRequestAsync(requestMessage); var response = await res.Content.ReadAsStringAsync(); isfavourite = response.Contains("3") ? true : false; //if (response.Contains("3")) // isfavourite = true; //else // isfavourite = false; return(isfavourite); } catch { return(false); } }
public async Task <user> GetUserByMailAsync(string email) { string completeUri = "http://childappapiservice.azurewebsites.net/api/users?email=" + email; Uri requestUri = new Uri(completeUri); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); user getUser = ReadToObject(httpResponseBody); return(getUser); } catch (Exception ex) { return(null); } }
public static async Task <Windows.Storage.Streams.IRandomAccessStream> GetStreamFromUrl(string url) { Windows.Storage.Streams.IRandomAccessStream returnStream = null; try { using (var cli = new Windows.Web.Http.HttpClient()) { var resp = await cli.GetAsync(new Uri(url)); var b = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); if (resp != null && resp.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { using (var stream = await resp.Content.ReadAsInputStreamAsync()) { var memStream = new MemoryStream(); if (memStream != null) { await stream.AsStreamForRead().CopyToAsync(memStream); memStream.Position = 0; returnStream = memStream.AsRandomAccessStream(); } } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error while downloading the attachment: " + e.Message); } return(returnStream); }
async Task <bool> TryConnect() { bool result = false; var client = new Windows.Web.Http.HttpClient(); client.DefaultRequestHeaders.Add("device-id", deviceId.ToString()); client.DefaultRequestHeaders.Add("device-message", "Hello from RPi2"); var response = client.GetAsync(new Uri("http://egholservice.azurewebsites.net/api/DeviceConnect"), HttpCompletionOption.ResponseContentRead); response.AsTask().Wait(); var responseResult = response.GetResults(); if (responseResult.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { result = true; var received = await responseResult.Content.ReadAsStringAsync(); Debug.WriteLine("Recieved - " + received); } else { Debug.WriteLine("TryConnect Failed - " + responseResult.StatusCode); } return(result); }
private static async Task <string> EncryptedPassword(string passWord) { string base64String; try { HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter(); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(httpBaseProtocolFilter); string url = "https://passport.bilibili.com/api/oauth2/getKey"; string content = $"appkey={ApiHelper.AndroidKey.Appkey}&mobi_app=android&platform=android&ts={ApiHelper.GetTimeSpan}"; content += "&sign=" + ApiHelper.GetSign(content); string stringAsync = await WebClientClass.PostResults(new Uri(url), content); JObject jObjects = JObject.Parse(stringAsync); string str = jObjects["data"]["hash"].ToString(); string str1 = jObjects["data"]["key"].ToString(); string str2 = string.Concat(str, passWord); string str3 = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim(); byte[] numArray = Convert.FromBase64String(str3); AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0); IBuffer buffer = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null); base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer)); } catch (Exception) { base64String = passWord; } return(base64String); }
public static async Task <Windows.Web.Http.HttpResponseMessage> SendFeedback(Feedback fb, bool sendLogs) { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("X-ZUMO-APPLICATION", "SBEhmMRzWBrKTGXfDkhVNGfXmsSrzv88"); if (sendLogs) { fb.BackendLog = await FileIO.ReadTextAsync(_backendLogFile) ?? "None"; fb.FrontendLog = await FileIO.ReadTextAsync(_frontendLogFile) ?? "None"; } else { fb.BackendLog = fb.FrontendLog = "None"; } var jsonSer = new DataContractJsonSerializer(typeof(Feedback)); var ms = new MemoryStream(); jsonSer.WriteObject(ms, fb); ms.Position = 0; var sr = new StreamReader(ms); var theContent = new StringContent(sr.ReadToEnd(), System.Text.Encoding.UTF8, "application/json"); var str = await theContent.ReadAsStringAsync(); var result = await httpClient.PostAsync(new Uri(Strings.FeedbackAzureURL), new HttpStringContent(str, UnicodeEncoding.Utf8, "application/json")); return(result); }
//private void GroupItemsPage_SizeChange(object sender, SizeChangedEventArgs e) //{ // if (e.NewSize.Width < 500) // { // VisualStateManager.GoToState(this, "MinimalLayaout", true); // } // else if (e.NewSize.Width < e.NewSize.Height) // { // VisualStateManager.GoToState(this, "PortraitLayout", true); // } // else // { // VisualStateManager.GoToState(this, "DefaultLayaout", true); // } //} //this method get json data from page and save those at observablecolletion private async Task TryPostJsonAsync() { currentpage = 1; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var headers = httpClient.DefaultRequestHeaders; Uri requestUri = new Uri("https://www.reddit.com//top/.json"); Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); var obj = JsonConvert.DeserializeObject <Model.RootObject>(httpResponseBody, new JsonSerializerSettings() { Culture = CultureInfo.CurrentCulture }); collectionItemsData2 = new ObservableCollection <Data2>((from r in obj.data.children select r.data).ToList()); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } }
public async Task <symbol[]> GetUserCounterAsync(symbol userSymbol) { string completeUri = "http://childappapiservice.azurewebsites.net/api/counters?email=" + userSymbol.email + "&symbolName=" + userSymbol.symbolName; Uri requestUri = new Uri(completeUri); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); symbol[] userSymbolUsage = JsonConvert.DeserializeObject <symbol[]>(httpResponseBody); return(userSymbolUsage); } catch (Exception ex) { return(null); } }
public async static Task <bool> SendMessage(string body) { // Namespace info. //var serviceNamespace = "sudhesh"; //var hubName = "test"; //var deviceName = "tisensortag"; //var sharedAccessPolicyName = "all"; //var sharedAccessKey = "ZcfdxuLADoYv3zQycbpddoelgBvogPxnqM7/dfMdU2k="; var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceNamespace, hubName, deviceName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceNamespace, hubName, deviceName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(body) }; //request.Headers.Add("Authorization", sas); //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var nowait = await webClient.SendRequestAsync(request); return(nowait.IsSuccessStatusCode); }
public static async Task <string> GetEncryptedPassword(string passWord) { string base64String; try { //https://secure.bilibili.com/login?act=getkey&rnd=4928 //https://passport.bilibili.com/login?act=getkey&rnd=4928 HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter(); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(httpBaseProtocolFilter); //WebClientClass wc = new WebClientClass(); string stringAsync = await httpClient.GetStringAsync((new Uri("https://passport.bilibili.com/login?act=getkey&rnd=" + new Random().Next(1000, 9999), UriKind.Absolute))); JObject jObjects = JObject.Parse(stringAsync); string str = jObjects["hash"].ToString(); string str1 = jObjects["key"].ToString(); string str2 = string.Concat(str, passWord); string str3 = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim(); byte[] numArray = Convert.FromBase64String(str3); AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0); IBuffer buffer = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null); base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer)); } catch (Exception) { //throw; base64String = passWord; } return(base64String); }
/// <summary> /// Posts a string with the rights of your Account to a given <paramref name="location"/>.. /// </summary> /// <returns>The Result if any exists. Doesn't handle exceptions</returns> /// <param name="location">The url sub-address like "http://192.168.1.2/<paramref name="location"/>"</param> /// <param name="arguments">The string to post tp the address</param> internal override string PostString(string location, string arguments) { string strResponseValue = string.Empty; Debug.WriteLine("This was searched:"); Debug.WriteLine(EndPoint + location + "?apikey=" + ApiKey); //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var headers = httpClient.DefaultRequestHeaders; headers.Add("X-Api-Key", ApiKey); Uri requestUri = new Uri(EndPoint + location); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { HttpStringContent arg = new HttpStringContent(arguments); //Send the GET request httpResponse = httpClient.PostAsync(requestUri, arg).AsTask().GetAwaiter().GetResult(); //httpResponse.EnsureSuccessStatusCode(); httpResponseBody = httpResponse.Content.ReadAsStringAsync().AsTask().GetAwaiter().GetResult(); strResponseValue = httpResponseBody; } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } return(strResponseValue); }
public async Task<bool> SendMessage(EventHubSensorMessage message) { // get a hold of the current application app = App.Current as SensorTagReader.App; string json = JsonConvert.SerializeObject(message, new JsonSerializerSettings() { Culture = new CultureInfo("en-US") }); var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceBusNamespace, eventHubName, message.SensorName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessPolicyKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceBusNamespace, eventHubName, message.SensorName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); // display the message that we are going to send app.Messages = "sending..." + json; var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(json) }; var nowait = await webClient.SendRequestAsync(request); return nowait.IsSuccessStatusCode; }
private static HttpClient CreateHttpClient (List<KeyValuePair<string, string>> headerParameters) { var httpClient = new HttpClient(); if (headerParameters != null) { foreach (var headerParameter in headerParameters) { httpClient.DefaultRequestHeaders.Append(headerParameter.Key, headerParameter.Value); } } return httpClient; }
/// <summary> /// Sends a layout request to server and returns the HTTP response, if any. /// </summary> /// <param name="apiId">optional api id, overrides the given id by SDKData.</param> /// <returns>A HttpResponseMessage containing the server response or null in case of an error.</returns> public async Task<ResponseMessage> RetrieveLayoutResponse(string apiId) { Logger.Trace("RetrieveLayoutResponse"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(Configuration.LayoutUri); HttpClient apiConnection = new HttpClient(baseProtocolFilter); apiConnection.DefaultRequestHeaders.Add(Constants.XApiKey, string.IsNullOrEmpty(apiId) ? Configuration.ApiKey : apiId); apiConnection.DefaultRequestHeaders.Add(Constants.Xiid, SdkData.DeviceId); string geoHash = await ServiceManager.LocationService.GetGeoHashedLocation(); if (!string.IsNullOrEmpty(geoHash)) { apiConnection.DefaultRequestHeaders.Add(Constants.Xgeo, geoHash); } apiConnection.DefaultRequestHeaders.Add(Constants.AdvertisementIdentifierHeader, string.IsNullOrEmpty(SdkData.UserId) ? Windows.System.UserProfile.AdvertisingManager.AdvertisingId : SdkData.UserId); HttpResponseMessage responseMessage; try { responseMessage = await apiConnection.SendRequestAsync(requestMessage); } catch (Exception ex) { LastCallResult = NetworkResult.NetworkError; System.Diagnostics.Debug.WriteLine("LayoutManager.RetrieveLayoutResponseAsync(): Failed to send HTTP request: " + ex.Message); return new ResponseMessage() {IsSuccess = false}; } Logger.Trace("RetrieveLayoutResponse HTTPCode: {0}", responseMessage.StatusCode); if (responseMessage.IsSuccessStatusCode) { LastCallResult = NetworkResult.Success; return new ResponseMessage() { Content = responseMessage.Content.ToString(), Header = responseMessage.Headers.ToString(), StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode }; } LastCallResult = NetworkResult.UnknownError; return new ResponseMessage() {StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode}; }
/// <summary> /// 发送GET请求 返回服务器回复数据(string) /// </summary> /// <param name="url"></param> /// <returns></returns> async public static Task<string> SendGetRequestAsync(string url) { try { HttpClient client = new HttpClient(); Uri uri = new Uri(url); HttpResponseMessage response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } catch (Exception) { return null; } }
/// <summary> /// 发送POST请求 返回服务器回复数据(string) /// </summary> /// <param name="url"></param> /// <param name="formData"></param> /// <returns></returns> async public static Task<string> SendPostRequestAsync(string url, IEnumerable<KeyValuePair<string, string>> formData) { try { HttpClient client = new HttpClient(); Uri uri = new Uri(url); HttpResponseMessage response = await client.PostAsync(uri, new HttpFormUrlEncodedContent(formData)); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } catch (Exception) { return null; } }
/// <summary> /// 发送POST请求 返回服务器回复数据(string) /// </summary> /// <param name="url"></param> /// <param name="formData"></param> /// <returns></returns> public async static Task<string> SendPostRequestAsync(string url, IEnumerable<KeyValuePair<string, string>> formData) { try { HttpClient client = new HttpClient(); Uri uri = new Uri(url); HttpResponseMessage response = await client.PostAsync(uri, new HttpFormUrlEncodedContent(formData)); response.EnsureSuccessStatusCode(); var buffer = await response.Content.ReadAsBufferAsync(); return Encoding.UTF8.GetString(buffer.ToArray()); } catch (Exception ex) { PopupMessage.DisplayMessage(ex.Message); return null; } }
// private string DeviceId = ""; async Task<bool> TryConnect() { bool result = false; var client = new Windows.Web.Http.HttpClient(); client.DefaultRequestHeaders.Add("device-id", deviceId.ToString()); client.DefaultRequestHeaders.Add("device-message", "Hello from RPi2"); var response = client.GetAsync(new Uri("http://egholservice.azurewebsites.net/api/DeviceConnect"), HttpCompletionOption.ResponseContentRead); response.AsTask().Wait(); var responseResult = response.GetResults(); if (responseResult.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { result = true; var received = await responseResult.Content.ReadAsStringAsync(); Debug.WriteLine("Recieved - " + received); } else { Debug.WriteLine("TryConnect Failed - " + responseResult.StatusCode); } return result; }
public async Task<string> Generatehash512(string test) { string uri = "http://demo.mapsearch360.com/WSFacilities.svc/Generatehash512/?text=" + test; Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(httpRequestMessage); string data = await response.Content.ReadAsStringAsync(); string encryptedstring = (data.Split(new char[] { ':' }))[1].Trim(new char[] { '\\', '"', '}' }); return encryptedstring; }
public WinRtHttpClientHandler(IHttpFilter httpFilter) { _client = new rt.HttpClient(httpFilter); }
private static WinHttpClient GetHttpClient() { var client = new WinHttpClient(); var info = new EasClientDeviceInformation(); var currentAssemblyName = typeof( HttpClient ).GetTypeInfo().Assembly.GetName(); string userAgent = string.Format( UserAgentFormat, currentAssemblyName.Version.ToString( 2 ), info.OperatingSystem, info.SystemManufacturer, info.SystemProductName ); client.DefaultRequestHeaders.UserAgent.ParseAdd( userAgent ); return client; }
public void postXMLData1() { var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); GetAvailableServicesRequest _objAGR = new GetAvailableServicesRequest(); _objAGR.franchUserID = AppStatic.franchUserID; _objAGR.password = AppStatic.password; _objAGR.userID = AppStatic.userID; _objAGR.userKey = AppStatic.userKey; _objAGR.userName = AppStatic.userName; _objAGR.userRole = AppStatic.userRole; _objAGR.userStatus = AppStatic.userStatus; _objAGR.userType = AppStatic.userType; _objAGR.placeNameFrom = txtBFromLocationT.Text; _objAGR.placeNameTo = txtBToLocationT.Text; _objAGR.placeIDFrom = txtBFromID.Text; _objAGR.placeIDto = txtBToID.Text; _objAGR.placeCodeFrom = txtBFromCode.Text; _objAGR.placeCodeTo = txtBToCode.Text; string d = txtBDateTab.Text; System.DateTime dt = System.DateTime.ParseExact(d, "dd MMM yyyy", CultureInfo.InvariantCulture); string Date = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); _objAGR.journeyDate = Date; xmlUtility listings = new xmlUtility(); XDocument element = listings.getservice(_objAGR); string stringXml = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(stringXml, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); XDocument loadedData = XDocument.Parse(strXmlReturned); XDocument element1 = listings.getAvailableServicelayout(_objAGR); string stringXml1 = element1.ToString(); byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(stringXml1.ToString()); StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("HistoryTest1.xml", CreationCollisionOption.OpenIfExists); String historyTestContent = await FileIO.ReadTextAsync(file); using (var stream = await file.OpenStreamForWriteAsync()) { stream.Seek(0, SeekOrigin.End); stream.Write(fileBytes, 0, fileBytes.Length); } List<XElement> _list = (from t1 in loadedData.Descendants("wsResponse") select t1).ToList(); List<PlaceList> seatsList = new List<PlaceList>(); string _msg = ""; if (_list != null) { foreach (XElement _elemet in _list) { PlaceList _obj = new PlaceList(); _obj.message = _elemet.Element("message").Value.ToString(); seatsList.Add(_obj); } _msg = seatsList.FirstOrDefault().message.ToString(); } if (_msg != "FAILURE") { var sdata = loadedData.Descendants("service"). Select(x => new GetAvailableService { arrivalDate = x.Element("arrivalDate").Value, arrivalTime = x.Element("arrivalTime").Value, classID = x.Element("classID").Value, classLayoutID = x.Element("classLayoutID").Value, className = x.Element("className").Value, corpCode = x.Element("corpCode").Value, departureTime = x.Element("departureTime").Value, destination = x.Element("destination").Value, fare = x.Element("fare").Value, journeyDate = x.Element("journeyDate").Value, journeyHours = x.Element("journeyHours").Value, maxSeatsAllowed = x.Element("maxSeatsAllowed").Value, origin = x.Element("origin").Value, placeIDFrom = x.Element("biFromPlace").Element("placeID").Value, placeIDto = x.Element("biToPlace").Element("placeID").Value, refundStatus = x.Element("refundStatus").Value, routeNo = x.Element("routeNo").Value, seatsAvailable = x.Element("seatsAvailable").Value, seatStatus = x.Element("seatStatus").Value, serviceID = x.Element("serviceID").Value, startPoint = x.Element("startPoint").Value, studID = x.Element("stuID").Value, tripCode = x.Element("tripCode").Value, viaPlaces = x.Element("viaPlaces").Value }); foreach (var item in sdata) { GetAvailableService gas = new GetAvailableService(); gas.arrivalDate = item.arrivalDate; gas.arrivalTime = item.arrivalTime; gas.classID = item.classID; gas.classLayoutID = item.classLayoutID; gas.className = item.className; gas.corpCode = item.corpCode; gas.departureTime = item.departureTime; gas.destination = item.destination; gas.fare = item.fare; gas.journeyDate = item.journeyDate; gas.journeyHours = item.journeyHours; gas.maxSeatsAllowed = item.maxSeatsAllowed; gas.origin = item.origin; gas.placeIDFrom = item.placeIDFrom; gas.placeIDto = item.placeIDto; gas.refundStatus = item.refundStatus; gas.routeNo = item.routeNo; gas.seatsAvailable = item.seatsAvailable; gas.seatStatus = item.seatStatus; gas.serviceID = item.serviceID; gas.startPoint = item.startPoint; gas.studID = item.studID; gas.tripCode = item.tripCode; gas.viaPlaces = item.viaPlaces; availableservice.Add(gas); } ListMenuItems.ItemsSource = sdata; string MaxPriceresult = sdata.OrderByDescending(x => x.fare).Select(x => x.fare).FirstOrDefault().ToString(); if (MaxPriceresult != null) { txtBMaxPriceCurrent.Text = MaxPriceresult; txtBMaxPrice.Text = MaxPriceresult; maxPrice = Convert.ToInt32(MaxPriceresult); MaxPrice = Convert.ToInt32(MaxPriceresult); Thumb2PositionPrice = Convert.ToInt32(MaxPriceresult); } string MinPriceresult = sdata.OrderBy(x => x.fare).Select(x => x.fare).FirstOrDefault().ToString(); if (MinPriceresult != null) { txtBMinPrice.Text = MinPriceresult; txtBMinPriceCurrent.Text = MinPriceresult; minPrice = Convert.ToInt32(MinPriceresult); MinPrice = Convert.ToInt32(MinPriceresult); Thumb1PositionPrice = Convert.ToInt32(MinPriceresult); } ListMenuItemsFilterCorp.ItemsSource = sdata.Select(x => x.corpCode).Distinct().ToList(); ListMenuItemsFilterBusType.ItemsSource = sdata.Select(x => x.className).Distinct().ToList(); FilterFunVisible(); } else { FilterFunCollapsed(); } } catch (Exception ex) { LoaderPop.Visibility = Visibility.Collapsed; ErrorpopUp.Visibility = Visibility.Visible; ExceptionLog obj = new ExceptionLog(); Error objError = new Error(); objError.ErrorEx = ex.Message; obj.CreateLogFile(objError); } }).AsTask(); }
public async void postXMLData1() { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); xmlUtility listings = new xmlUtility(); getPlaceListRequest _objgetPlaceListRequest = listings.GetUserRequestParameters(); XDocument element = listings.getList(_objgetPlaceListRequest); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(strXmlReturned); XDocument loadedData = XDocument.Parse(strXmlReturned); var PlaceList = loadedData.Descendants("PlaceList"). Select(x => new PlaceList { PlaceID = x.Element("placeID").Value, PlaceCode = x.Element("placeCode").Value, PlaceName = x.Element("placeName").Value }); } catch (Exception ex) { ExceptionLog obj = new ExceptionLog(); Error objError = new Error(); objError.ErrorEx = ex.Message; obj.CreateLogFile(objError); } }
public async Task GetOAuthToken(string webAuthResultResponseData) { // // Acquiring a access_token first // string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("oauth_token")); string request_token = null; string oauth_verifier = null; String[] keyValPairs = responseData.Split('&'); for (int i = 0; i < keyValPairs.Length; i++) { String[] splits = keyValPairs[i].Split('='); switch (splits[0]) { case "oauth_token": request_token = splits[1]; break; case "oauth_verifier": oauth_verifier = splits[1]; break; } } String TwitterUrl = "https://api.twitter.com/oauth/access_token"; string timeStamp = GetTimeStamp(); string nonce = GetNonce(); string SigBaseStringParams = "oauth_consumer_key=" + TwitterClient.TwitterClientID.Text; SigBaseStringParams += "&" + "oauth_nonce=" + nonce; SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1"; SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp; SigBaseStringParams += "&" + "oauth_token=" + request_token; SigBaseStringParams += "&" + "oauth_version=1.0"; String SigBaseString = "POST&"; SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams); String Signature = GetSignature(SigBaseString); HttpStringContent httpContent = new HttpStringContent("oauth_verifier=" + oauth_verifier, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); string authorizationHeaderParams = "oauth_consumer_key=\"" + TwitterClient.TwitterClientID.Text + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_timestamp=\"" + timeStamp + "\", oauth_token=\"" + Uri.EscapeDataString(request_token) + "\", oauth_version=\"1.0\""; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("OAuth", authorizationHeaderParams); var httpResponseMessage = await httpClient.PostAsync(new Uri(TwitterUrl), httpContent); string response = await httpResponseMessage.Content.ReadAsStringAsync(); String[] Tokens = response.Split('&'); string oauth_token_secret = null; string access_token = null; string screen_name = null; for (int i = 0; i < Tokens.Length; i++) { String[] splits = Tokens[i].Split('='); switch (splits[0]) { case "screen_name": screen_name = splits[1]; break; case "oauth_token": access_token = splits[1]; break; case "oauth_token_secret": oauth_token_secret = splits[1]; break; } } //you can store access_token and oauth_token_secret for further use. See Scenario5(Account Management). if (access_token != null) { DebugPrint("access_token = " + access_token); } if (oauth_token_secret != null) { DebugPrint("oauth_token_secret = " + oauth_token_secret); } if (screen_name != null) { this.screen_name = screen_name; } this.o_auth_token = access_token; this.o_auth_token_secret = o_auth_token; }
private async void UploadFile(string url, StorageFile file) { try { Stream data = await file.OpenStreamForReadAsync(); if (data.Length > maxsize) throw new Exception("Файл не должен превышать 200 МБ."); var client = new Windows.Web.Http.HttpClient(); var content = new HttpMultipartFormDataContent(); content.Add(new HttpStreamContent(data.AsInputStream()), "file", file.Name); var postAsyncOp = client.PostAsync(new Uri(url), content); postAsyncOp.Progress = async (r, progress) => { if (progress.TotalBytesToSend.HasValue && progress.TotalBytesToSend > 0) { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { statusText.Text = Math.Round((((double)progress.BytesSent * 100) / progress.TotalBytesToSend.Value), 0).ToString() + " %"; }); } }; var result = await postAsyncOp; //fileToAdd = file; JSONAddedFileResponse = await result.Content.ReadAsStringAsync(); nameDocumentAdd.Text = fileToAdd.Name; uploadGrid.Visibility = Visibility.Collapsed; AddDocumentGrid.Visibility = Visibility.Visible; CommandBar.Visibility = Visibility.Collapsed; } catch(Exception e) { uploadGrid.Visibility = Visibility.Collapsed; AddDocumentGrid.Visibility = Visibility.Collapsed; CommandBar.Visibility = Visibility.Visible; MessageDialog dialog = new MessageDialog("Не удалось начать загрузку документа. " + e.Message); dialog.Commands.Add(new UICommand("Ок", new UICommandInvokedHandler(CommandHandlers))); await dialog.ShowAsync(); } }
public static async void Upload(string uri, Stream data, string paramName, string uploadContentType,Action<VKHttpResult> resultCallback, Action<double> progressCallback = null, string fileName = null) { #if SILVERLIGHT var rState = new RequestState(); rState.resultCallback = resultCallback; #endif try { #if SILVERLIGHT var request = (HttpWebRequest)WebRequest.Create(uri); request.AllowWriteStreamBuffering = false; rState.request = request; request.Method = "POST"; string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); string contentType = "multipart/form-data; boundary=" + formDataBoundary; request.ContentType = contentType; request.CookieContainer = new CookieContainer(); string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", formDataBoundary, paramName, fileName ?? "myDataFile", uploadContentType); string footer = "\r\n--" + formDataBoundary + "--\r\n"; request.ContentLength = Encoding.UTF8.GetByteCount(header) + data.Length + Encoding.UTF8.GetByteCount(footer); request.BeginGetRequestStream(ar => { try { var requestStream = request.EndGetRequestStream(ar); requestStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); StreamUtils.CopyStream(data, requestStream, progressCallback); requestStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); requestStream.Close(); request.BeginGetResponse(new AsyncCallback(ResponseCallback), rState); } catch (Exception ex) { Logger.Error("VKHttpRequestHelper.Upload failed to write data to request stream.", ex); SafeClose(rState); SafeInvokeCallback(rState.resultCallback, false, null); } }, null); #else var httpClient = new Windows.Web.Http.HttpClient(); HttpMultipartFormDataContent content = new HttpMultipartFormDataContent(); content.Add(new HttpStreamContent(data.AsInputStream()), paramName, fileName ?? "myDataFile"); content.Headers.Add("Content-Type", uploadContentType); var postAsyncOp = httpClient.PostAsync(new Uri(uri, UriKind.Absolute), content); postAsyncOp.Progress = (r, progress) => { if (progressCallback != null && progress.TotalBytesToSend.HasValue && progress.TotalBytesToSend > 0) { progressCallback(((double)progress.BytesSent * 100) / progress.TotalBytesToSend.Value); } }; var result = await postAsyncOp; var resultStr = await result.Content.ReadAsStringAsync(); SafeInvokeCallback(resultCallback, result.IsSuccessStatusCode, resultStr); #endif } catch (Exception exc) { Logger.Error("VKHttpRequestHelper.Upload failed.", exc); #if SILVERLIGHT SafeClose(rState); SafeInvokeCallback(rState.resultCallback, false, null); #else SafeInvokeCallback(resultCallback, false, null); #endif } }
public static async void DispatchHTTPRequest( string baseUri, Dictionary<string, string> parameters, Action<VKHttpResult> resultCallback) { Logger.Info(">>> VKHttpRequestHelper starting http request. baseUri = {0}; parameters = {1}", baseUri, GetAsLogString(parameters)); var queryString = ConvertDictionaryToQueryString(parameters, true); var requestState = new RequestState(); try { #if SILVERLIGHT requestState.resultCallback = resultCallback; var httpWebRequest = (HttpWebRequest)WebRequest.Create(baseUri); requestState.request = httpWebRequest; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.Method = "POST"; httpWebRequest.BeginGetRequestStream(ar => { try { var requestStream = httpWebRequest.EndGetRequestStream(ar); using (var sw = new StreamWriter(requestStream)) { sw.Write(queryString); } httpWebRequest.BeginGetCompressedResponse( new AsyncCallback(ResponseCallback), requestState); } catch (Exception exc) { Logger.Error("VKHttpRequestHelper.DispatchHTTPRequest failed.", exc); SafeClose(requestState); SafeInvokeCallback(requestState.resultCallback, false, null); } }, null); #else var filter = new HttpBaseProtocolFilter(); filter.AutomaticDecompression = true; var httpClient = new Windows.Web.Http.HttpClient(filter); HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(parameters); var result = await httpClient.PostAsync(new Uri(baseUri, UriKind.Absolute), content); var resultStr = await result.Content.ReadAsStringAsync(); SafeInvokeCallback(resultCallback, result.IsSuccessStatusCode, resultStr); #endif } catch (Exception exc) { Logger.Error("VKHttpRequestHelper.DispatchHTTPRequest failed.", exc); #if SILVERLIGHT SafeClose(requestState); SafeInvokeCallback(requestState.resultCallback, false, null); #else SafeInvokeCallback(resultCallback, false, null); #endif } }
public async Task<string> UploadImage2(byte[] image, string url) { Stream stream = new System.IO.MemoryStream(image); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); Uri resourceAddress = null; Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress); Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress); request.Content = streamContent; var httpClient = new Windows.Web.Http.HttpClient(); var cts = new CancellationTokenSource(); Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); response.EnsureSuccessStatusCode(); string result =await response.Content.ReadAsStringAsync(); return result; }
public async void postXMLData1() { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); xmlUtility listings = new xmlUtility(); getPlaceListRequest _objgetPlaceListRequest = listings.GetUserRequestParameters(); XDocument element = listings.getList(_objgetPlaceListRequest); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(strXmlReturned); StorageFile files = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("PlaceNames.xml", CreationCollisionOption.ReplaceExisting); String historyTestContent = await FileIO.ReadTextAsync(files); using (var stream = await files.OpenStreamForWriteAsync()) { stream.Write(fileBytes, 0, fileBytes.Length); } LoderPopup.Visibility = Visibility.Collapsed; } catch (Exception ex) { LoderPopup.Visibility = Visibility.Collapsed; ExceptionLog obj = new ExceptionLog(); Error objError = new Error(); objError.ErrorEx = ex.Message; obj.CreateLogFile(objError); } }
private async void Button_Click1(object sender, RoutedEventArgs e) { string apiUrl = "http://mobiledatawebapi.azurewebsites.net/api/MobileData"; Uri apiUrl2 = new Uri("http://mobiledatawebapi.azurewebsites.net/api/MobileData"); var locationInfo = new LocationInfo() { Id = Guid.NewGuid(), Latitude = _latitude, Longitude = _longitude, County = _region }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(locationInfo); HttpClient httpClient = new HttpClient(); HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), new Uri(apiUrl)); msg.Content = new HttpStringContent(json); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); HttpResponseMessage response1 = await httpClient.GetAsync(apiUrl2).AsTask(); var content = response1.Content; var t = content.ReadAsStringAsync().GetResults(); if (locationInfo.County != null) { if (content != null) { if (content.ReadAsStringAsync().GetResults().Contains(locationInfo.County)) { statustxt.Text = "County Already Set"; } else { HttpResponseMessage response = await httpClient.SendRequestAsync(msg).AsTask(); btnSend.Visibility = Visibility.Collapsed; statustxt.Text = "Sent Successfully!"; } } } }
public async Task<string> GetTwitterRequestTokenAsync(string twitterCallbackUrl, string consumerKey) { // // Acquiring a request token // string TwitterUrl = "https://api.twitter.com/oauth/request_token"; string nonce = GetNonce(); string timeStamp = GetTimeStamp(); string SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString(twitterCallbackUrl); SigBaseStringParams += "&" + "oauth_consumer_key=" + consumerKey; SigBaseStringParams += "&" + "oauth_nonce=" + nonce; SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1"; SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp; SigBaseStringParams += "&" + "oauth_version=1.0"; string SigBaseString = "GET&"; SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams); string Signature = GetSignature(SigBaseString); TwitterUrl += "?" + SigBaseStringParams + "&oauth_signature=" + Uri.EscapeDataString(Signature); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); string GetResponse = await httpClient.GetStringAsync(new Uri(TwitterUrl)); // DebugPrint("Received Data: " + GetResponse); string request_token = null; string oauth_token_secret = null; string[] keyValPairs = GetResponse.Split('&'); for (int i = 0; i < keyValPairs.Length; i++) { string[] splits = keyValPairs[i].Split('='); switch (splits[0]) { case "oauth_token": request_token = splits[1]; break; case "oauth_token_secret": oauth_token_secret = splits[1]; break; } } o_auth_token = request_token; DebugPrint(o_auth_token); return request_token; }
public static async Task<string> GetEncryptedPassword(string passWord) { string base64String; try { //https://secure.bilibili.com/login?act=getkey&rnd=4928 //https://passport.bilibili.com/login?act=getkey&rnd=4928 HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter(); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(httpBaseProtocolFilter); //WebClientClass wc = new WebClientClass(); string stringAsync = await httpClient.GetStringAsync((new Uri("https://secure.bilibili.com/login?act=getkey&rnd=" + new Random().Next(1000,9999), UriKind.Absolute))); JObject jObjects = JObject.Parse(stringAsync); string str = jObjects["hash"].ToString(); string str1 = jObjects["key"].ToString(); string str2 = string.Concat(str, passWord); string str3 = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim(); byte[] numArray = Convert.FromBase64String(str3); AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0); IBuffer buffer = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null); base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer)); } catch (Exception) { throw; //base64String = pw; } return base64String; }