/// <summary> /// Gets connection level for the current Wifi Connection. /// </summary> /// <returns> string value of level/></returns> /// public static async Task <bool> GetNetworkLevelUsingGoogle() { if (!headers.UserAgent.TryParseAdd(WP_USER_AGENT)) { throw new Exception("Invalid header value: " + WP_USER_AGENT); } //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 { //Send the GET request httpResponse = await httpClient.GetAsync(new Uri(checkInternetUriString)); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch { return(false); } var succes = httpResponseBody.Contains("authlogin"); var gSuccess = httpResponseBody.Contains("Google"); if (!succes) { return(true); } else { return(false); } }
public async Task <HttpResponseMessage> GetUrlAsync(string url) { string token = await GetAccessTokenAsync(); // Add the access token to the Authorization Header of the call to the Graph API, and call the Graph API. httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", token); HttpResponseMessage response = await httpClient.GetAsync(new Uri(url)); return(response); }
public static async Task <Quiz[]> GetQuizzesFromIdHashAsync(string userIdHash) { UriBuilder quizzesBaseUriBuilder = new UriBuilder("http://localhost:55418/api/Quizzes/userIdHash/" + userIdHash); // quizzesBaseUriBuilder.Query = "UserIdHash=" + userIdHash + "; var result = await httpClient.GetAsync(quizzesBaseUriBuilder.Uri); var json = await result.Content.ReadAsStringAsync(); var quizList = JsonConvert.DeserializeObject <Quiz[]>(json); return(quizList); }
public async Task <string> SendGetRequestAsync(string url) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(nameof(url)); } var uri = new Uri(url); var filter = new HttpBaseProtocolFilter(); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); using (var httpClient = new Windows.Web.Http.HttpClient(filter)) { try { var responseString = string.Empty; //var request = new HttpRequestMessage(HttpMethod.Get, uri); var response = await httpClient.GetAsync(uri); if (response.IsSuccessStatusCode) { responseString = await response.Content.ReadAsStringAsync(); } return(responseString); } catch (Exception exception) //for debugging { throw; } } }
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 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; }
/// <summary> /// A Get request for any String using your Account /// </summary> /// <returns>The result as a String, doesn't handle Exceptions</returns> /// <param name="location">The url sub-address like "http://192.168.1.2/<paramref name="location"/>"</param> internal override string Get(string location) { 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.Add("X-Api-Key", ApiKey); //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 { //Send the GET request httpResponse = httpClient.GetAsync(requestUri).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 <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 <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 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 <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); }
/// <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 }
//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 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("登录失败"); } }
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 = ""; }
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); } }
public static async Task <IEnumerable <UnityPrimitive> > FetchSceneData() { var url = string.Format(UrlTemplate, "GetObjects"); var uri = new Uri(url); #if UNITY_EDITOR var webClient = new WebClient(); var json = await webClient.DownloadStringTaskAsync(uri); return(JsonConvert.DeserializeObject <IEnumerable <UnityPrimitive> >(json)); #else var client = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpResponseMessage response = await client.GetAsync(uri); IEnumerable <UnityPrimitive> result = null; if (response.IsSuccessStatusCode) { var stringres = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <IEnumerable <UnityPrimitive> >(stringres); } return(result); #endif }
/// <summary> /// 通过API获取物品信息 /// </summary> /// <returns></returns> public static async Task <string> GetItemDataAsync() { string url = "http://www.dota2.com.cn/items/json"; Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(); var response = await http.GetAsync(new Uri(url)); var jsonMessage = await response.Content.ReadAsStringAsync(); return(jsonMessage); }
public static async Task <string> GetItemDataENAsync() { string url = String.Format("http://www.dota2.com/jsfeed/itemdata"); Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(); var response = await http.GetAsync(new Uri(url)); var jsonMessage = await response.Content.ReadAsStringAsync(); return(jsonMessage); }
public async Task <IEnumerable <Person> > GetPeople(string excludeIds, int deviceId) { var result = Enumerable.Empty <Person>(); var uriBuilder = new UriBuilder(ApiBaseUrl) { Path = "api/People", Query = $"excludeIds={excludeIds}&deviceId={deviceId}" }; try { //Send the GET request var httpResponse = await _httpClient.GetAsync(uriBuilder.Uri); if (!httpResponse.IsSuccessStatusCode) { return(null); } var httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); //guarded parse if (string.IsNullOrEmpty(httpResponseBody)) { return(null); } result = JObject.Parse(httpResponseBody).SelectToken("People").ToObject <List <Person> >(); return(result); } catch (JsonSerializationException jex) { //todo log error Debug.WriteLine(jex.Message); } catch (HttpRequestException httpex) { // Handle failure Debug.WriteLine(httpex.Message); } catch (Exception ex) { Debug.WriteLine(ex.Message); } return(result); }
public async Task <List <Uposlenik> > dajSveUposlenike() { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var headers = httpClient.DefaultRequestHeaders; string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } string url = "http://localhost:50180/Uposleniks/GetSve"; Uri requestUri = new Uri(url); 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(); string json = httpResponseBody; JsonConverter[] converters = { new UposlenikConverter() }; var test = JsonConvert.DeserializeObject <List <Uposlenik> >(json, new JsonSerializerSettings() { Converters = converters }); return(test); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } return(null); }
public async Task <string> getConnectToTranslateAsync(string queryString) { //Create an HTTP client Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } //appid+q+salt+密钥 Uri requestUri = new Uri("http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + queryString + "&from=en&to=zh&appid=20180424000149859&salt=1435660288&sign=" + GetMD5WithString(get_uft8("20180424000149859" + queryString + "1435660288" + "Jwjp6uJTHbN2YUX7DwNW"))); //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 { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); //"{\"from\":\"en\",\"to\":\"zh\",\"trans_result\":[{\"src\":\"apple\",\"dst\":\"\\u82f9\\u679c\"}]}" res = httpResponseBody.ToString(); JsonObject temp = JsonObject.Parse(res); JArray jlist = JArray.Parse(temp["trans_result"].ToString()); //jp = (JsonObject)JsonConvert.DeserializeObject(res); return(jlist[0]["dst"].ToString()); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; return(httpResponseBody); } }
public static async Task <string> GetReroutedUrl(string url) { string returnString = url; try { using (var cli = new Windows.Web.Http.HttpClient()) { var resp = await cli.GetAsync(new Uri(url)); if (resp != null && resp.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { if ((resp.RequestMessage != null) && (resp.RequestMessage.RequestUri != null)) { IReadOnlyDictionary <string, string> param = ParseQueryString(resp.RequestMessage.RequestUri); if (param != null) { if ( (param.ContainsKey("resid")) && (param.ContainsKey("authkey"))) { string resid = param["resid"]; string authkey = param["authkey"]; authkey = authkey.Replace("!", "%21"); char[] sep = { '!' }; string[] array = resid.Split(sep); if (array.Length == 2) { string residprefix = array[0]; string residsuffix = "%21" + array[1]; resid = resid.Replace("!", "%21"); returnString = "https://onedrive.live.com/download.aspx?cid=" + residprefix + "&authKey=" + authkey + "&resid=" + resid; } } } } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error while downloading the attachment: " + e.Message); } return(returnString); }
/// <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; } }
public async Task GetTest() { //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json"); //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 { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); Debug.WriteLine("Output: " + httpResponseBody); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } }
// 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; }
private async void nuevo_Click(object sender, RoutedEventArgs e) { var uri = new Uri($"http://mancalaapi.azurewebsites.net/api/tableros/new/0/4/4/4/4/4/4/4/4/4/4/4/4"); var httpClient = new Windows.Web.Http.HttpClient(); try { var result = await httpClient.GetAsync(uri); DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(int)); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(result.Content.ToString())); int id = (int)js.ReadObject(stream); Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(mancalap1api), id); } catch { } }
/// <summary> /// 获得图片 /// </summary> async void initGetImage() { try { // StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/srca.cer")); string uriStr = ""; uriStr = "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand"; Uri uri = new Uri(uriStr); // client.DefaultRequestHeaders.Add() Windows.Web.Http.HttpResponseMessage respon = await client.GetAsync(uri); if (respon != null && respon.StatusCode == HttpStatusCode.Ok) { BitmapImage bmp = new BitmapImage(); using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { await respon.Content.WriteToStreamAsync(stream); stream.Seek(0UL); bmp.SetSource(stream); image.Source = bmp; image.Width = bmp.PixelWidth; image.Height = bmp.PixelHeight; } } else { Debug.Write("log cuowu"); } } catch { Debug.Write("log cuowu"); } }
/* * ----< Function > TruncateTestFunctions * ----< Description > * This function will truncate any items in the test function table of the api database * ----< Description > * @Param None * @Return None */ public static async void TruncateTestFunctions() { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.Headers.HttpRequestHeaderCollection headers = httpClient.DefaultRequestHeaders; string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("http://www.kaminfay.com/"); 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(); Debug.WriteLine(httpResponseBody); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } }
public async Task <string> getConnectToGetWeatherAsync(string queryString) { //Create an HTTP client Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } //Uri requestUri = new Uri("http://v.juhe.cn/weather/index?format=2&cityname="+queryString+"&key=c8f3ebd5bd91ab7aa0a9be9cc717e5dd"); Uri requestUri = new Uri("http://v.juhe.cn/weather/index?cityname=" + queryString + "&dtype=xml&format=2&key=c8f3ebd5bd91ab7aa0a9be9cc717e5dd"); //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 { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); return(queryString + ":" + getStringFromWeatherXMLString(httpResponseBody)); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; return(res); } }
public virtual async Task <string> get(Uri link) { var cts = new CancellationTokenSource(); cts.CancelAfter(1000); try { var response = await client.GetAsync(link); if (response == null || !response.IsSuccessStatusCode) { return(string.Empty); } string cont = await response.Content.ReadAsStringAsync(); return(cont); } catch (Exception e) { return(string.Empty); } }
public static async Task<string> LoginBilibili(string UserName, string Password) { try { //发送第一次请求,得到access_key WebClientClass wc = new WebClientClass(); string results =await wc.GetResults(new Uri("https://api.bilibili.com/login?appkey=422fd9d7289a1dd9&platform=wp&pwd=" +WebUtility.UrlEncode(Password) + "&type=json&userid=" + WebUtility.UrlEncode(UserName))); //Json解析及数据判断 LoginModel model = new LoginModel(); model = JsonConvert.DeserializeObject<LoginModel>(results); if (model.code == -627) { return "登录失败,密码错误!"; } if (model.code == -626) { return "登录失败,账号不存在!"; } if (model.code == -625) { return "密码错误多次"; } if (model.code==-628) { return "未知错误"; } if (model.code == -1) { return "登录失败,程序注册失败!请联系作者!"; } Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient(); if (model.code == 0) { access_key = model.access_key; Windows.Web.Http.HttpResponseMessage hr2 = await hc.GetAsync(new Uri("http://api.bilibili.com/login/sso?&access_key=" + model.access_key + "&appkey=422fd9d7289a1dd9&platform=wp")); hr2.EnsureSuccessStatusCode(); StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.CreateFileAsync("us.bili", CreationCollisionOption.OpenIfExists); await FileIO.WriteTextAsync(file, model.access_key); } //看看存不存在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")) { return "登录成功"; } else { return "登录失败"; } } catch (Exception) { return "登录发生错误"; } }
public async Task <Potrosac> dajPotrosaca(string jmbg) { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var headers = httpClient.DefaultRequestHeaders; string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } string url = "http://localhost:50180/Potrosacs/GetJMBG?JMBG=" + jmbg; //Uri requestUri = new Uri("http://localhost:50180/Potrosacs/GetAccount?Email" + EMail + "&password="******""; try { httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); string json = httpResponseBody; novi = JsonConvert.DeserializeObject <Potrosac>(json); return(novi); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } return(null); /*try * { * Trazeni = null; * Trazeni = await Task.Run(() => Baza.Instanca.dajPotrosaca(Jmbg)); * * if (Trazeni != null) * { * Found = true; * var dialog = new MessageDialog("Uspjesno pronadjen potrosac!"); * await dialog.ShowAsync(); * } * else * { * Found = false; * var dialog = new MessageDialog("Nije pronadjen potrosac."); * await dialog.ShowAsync(); * } * } * catch(Exception) * { * * }*/ }
public static async Task <string> LoginBilibili(string UserName, string Password) { try { //https://api.bilibili.com/login?appkey=422fd9d7289a1dd9&platform=wp&pwd=JPJclVQpH4jwouRcSnngNnuPEq1S1rizxVJjLTg%2FtdqkKOizeIjS4CeRZsQg4%2F500Oye7IP4gWXhCRfHT6pDrboBNNkYywcrAhbOPtdx35ETcPfbjXNGSxteVDXw9Xq1ng0pcP1burNnAYtNRSayEKC1jiugi1LKyWbXpYE6VaM%3D&type=json&userid=xiaoyaocz&sign=74e4c872ec7b9d83d3a8a714e7e3b4b3 //发送第一次请求,得到access_key string url = "https://api.bilibili.com/login?appkey=422fd9d7289a1dd9&platform=wp&pwd=" + WebUtility.UrlEncode(await GetEncryptedPassword(Password)) + "&type=json&userid=" + WebUtility.UrlEncode(UserName); url += "&sign=" + ApiHelper.GetSign(url); string results = await WebClientClass.GetResults(new Uri(url)); //Json解析及数据判断 LoginModel model = new LoginModel(); model = JsonConvert.DeserializeObject <LoginModel>(results); if (model.code == -627) { return("登录失败,密码错误!"); } if (model.code == -626) { return("登录失败,账号不存在!"); } if (model.code == -625) { return("密码错误多次"); } if (model.code == -628) { return("未知错误"); } if (model.code == -1) { return("登录失败,程序注册失败!请联系作者!"); } Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient(); if (model.code == 0) { access_key = model.access_key; Windows.Web.Http.HttpResponseMessage hr2 = await hc.GetAsync(new Uri("http://api.bilibili.com/login/sso?&access_key=" + model.access_key + "&appkey=422fd9d7289a1dd9&platform=wp")); hr2.EnsureSuccessStatusCode(); SettingHelper.Set_Access_key(model.access_key); } //看看存不存在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")) { return("登录成功"); } else { return("登录失败"); } } catch (Exception ex) { if (ex.HResult == -2147012867) { return("登录失败,检查你的网络连接!"); } else { return("登录发生错误"); } } }
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; }
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!"; } } } }