private async void SendData() { pairs.Clear(); pairs.Add("country", country.Text); pairs.Add("airport", airport.Text); HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs); await clientOb.PostAsync(connectionUri, formContent); Windows.Web.Http.HttpResponseMessage response = await clientOb.PostAsync(connectionUri, formContent); if (!response.IsSuccessStatusCode) { var dialog = new MessageDialog("Error while Adding a trip", "Error"); await dialog.ShowAsync(); } else { responseBodyAsText = await response.Content.ReadAsStringAsync(); responseBodyAsText = responseBodyAsText.Replace("<br>", Environment.NewLine); // Insert new lines if (responseBodyAsText.Substring(13, 2).Equals("ko")) { var dialog = new MessageDialog("Error in Adding", "Error"); await dialog.ShowAsync(); } else { { var dialog = new MessageDialog("Trip Added", "Added"); await dialog.ShowAsync(); } } } }
private async void ButtonWindowsWebHttp_OnClick(object sender, RoutedEventArgs e) { var httpBaseProtocolFilter = new HttpBaseProtocolFilter { AllowUI = true, CacheControl = { ReadBehavior = HttpCacheReadBehavior.NoCache, WriteBehavior = HttpCacheWriteBehavior.NoCache } }; HttpCookieManager cookieManager = httpBaseProtocolFilter.CookieManager; List <HttpCookie> cookies = cookieManager.GetCookies(_uri).ToList(); using (var httpClient = new HttpClient(httpBaseProtocolFilter)) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, _uri); Request.Text = new StringBuilder().AppendLine(requestMessage.ToString()) .AppendLine(requestMessage.Headers.ToString()) .AppendLine(string.Join("\n", cookies)).ToString(); HttpResponseMessage responseMessage = await httpClient.SendRequestAsync(requestMessage); Request1.Text = new StringBuilder().AppendLine(responseMessage.RequestMessage.ToString()) .AppendLine(string.Join(" - ", cookies)).ToString(); Response.Text = responseMessage.ToString(); } }
public static async Task <string> CookiedPostForm(string url, string referrer, KeyValuePair <string, string>[] keyValues) { //HttpResponseMessage response = null; try { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)); HttpFormUrlEncodedContent cont = new HttpFormUrlEncodedContent(keyValues); req.Content = cont; req.Headers.Referer = new Uri(referrer); HttpResponseMessage hc = await client.SendRequestAsync(req); //await ShowMessageDialog("响应", hc.Content.ToString()); req.Dispose(); return(hc.Content.ToString()); } catch (COMException e) { return("Cannot get response"); } }
//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 <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 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 async Task <HttpResponseMessage> SendAsync(CancellationToken token = default(CancellationToken), Progress <HttpProgress> progressCallback = null) { using (var request = new HttpRequestMessage(_method, _requestUrl)) using (_contentStream) { request.Headers.Connection.Add(new HttpConnectionOptionHeaderValue("Keep-Alive")); request.Headers.UserAgent.Add(HttpProductInfoHeaderValue.Parse("Mozilla/5.0")); if (_customHeaders != null) { foreach (var header in _customHeaders) { request.Headers.Add(header); } } if (_method.Method == "PROPFIND") { request.Content = new HttpStringContent(PropfindContent, UnicodeEncoding.Utf8); } else if (_contentStream != null) { request.Content = new HttpStreamContent(_contentStream.AsInputStream()); } HttpResponseMessage response = await _httpClient.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead).AsTask(token, progressCallback); return(response); } }
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 async Task <string> GetData() { var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); var webService = PeripheralInfo.IP + WebServiceGetBuffer; var resourceUri = new Uri(webService); try { Windows.Web.Http.HttpResponseMessage response = await httpClient.PostAsync(resourceUri, null); var message = await response.Content.ReadAsStringAsync(); if (message != "") { OnReceivedData(DataHandling.DataConversion.StringToListByteArray(message).ToArray()); } response.Dispose(); cts.Dispose(); return(message); } catch (TaskCanceledException ex) { // Handle request being canceled due to timeout. Debug.WriteLine(ex.Message); return(""); } 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 = ""; }
/// <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 static async Task <UnityPrimitive> CreateObject(UnityPrimitive updatedObject) #endif { //Here is an example of how to use WebClient class and HttpClient class in UWP var url = string.Format(UrlTemplate, "CreateObject"); var data = JsonConvert.SerializeObject(updatedObject, Formatting.Indented); #if UNITY_EDITOR var webClient = new WebClient(); webClient.Headers["content-type"] = "application/json"; /* Always returns a byte[] array data as a response. */ var response_data = webClient.UploadString(url, "POST", data); // Parse the returned data (if any) if needed. var responseString = response_data; Debug.LogWarning(responseString); return(JsonConvert.DeserializeObject <UnityPrimitive>(response_data)); #else var client = new Windows.Web.Http.HttpClient(); var content = new Windows.Web.Http.HttpStringContent(data, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"); Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(new Uri(url), content); UnityPrimitive result = null; if (response.IsSuccessStatusCode) { var stringres = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <UnityPrimitive>(stringres); } return(result); #endif }
/// <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 <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 <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 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 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); } }
private async Task <T> UnwrapGqlResposne <T>(HttpResponseMessage response) { return((await response.Content.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false)) .AsStreamForRead() .DeseriaizeJsonFromStream <ApiDataContainer>() .Data.First.First.ToObject <T>()); }
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); }
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 }
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 GetHoloPoints(object sender, object e) { var uri = new System.Uri("https://holotest-6cd6b.firebaseio.com/HoloPoints.json"); using (var httpClient = new Windows.Web.Http.HttpClient()) { // Always catch network exceptions for async methods try { //string result = "{\"FarBottomLeftX\":\" - 0.53\",\"FarBottomLeftY\":\" - 0.30\",\"FarBottomLeftZ\":\"2.08\",\"FarBottomRightX\":\"0.53\",\"FarBottomRightY\":\" - 0.30\",\"FarBottomRightZ\":\"2.08\",\"FarTopLeftX\":\" - 0.53\",\"FarTopLeftY\":\"0.30\",\"FarTopLeftZ\":\"2.08\",\"FarTopRightX\":\"0.53\",\"FarTopRightY\":\"0.30\",\"FarTopRightZ\":\"2.08\",\"NearBottomLeftX\":\" - 0.53\",\"NearBottomLeftY\":\" - 0.30\",\"NearBottomLeftZ\":\"0.00\",\"NearBottomRightX\":\"0.53\",\"NearBottomRightY\":\" - 0.30\",\"NearBottomRightZ\":\"0.00\",\"NearTopLeftX\":\" - 0.53\",\"NearTopLeftY\":\"0.30\",\"NearTopLeftZ\":\"0.00\",\"NearTopRightX\":\"0.53\",\"NearTopRightY\":\"0.30\",\"NearTopRightZ\":\"0.00\"}";//await httpClient.GetStringAsync(uri); string result = await httpClient.GetStringAsync(uri); Dictionary <string, Dictionary <string, string> > parentDict = JsonConvert.DeserializeObject <Dictionary <string, Dictionary <string, string> > >(result); Dictionary <string, string> childDict = parentDict.Values.First(); WebServiceTxt.Text = childDict["FarBottomLeftX"]; Point3D topLeftpt = new Point3D(); topLeftpt.x = float.Parse(childDict["NearTopLeftX"]); topLeftpt.y = float.Parse(childDict["NearTopLeftY"]); topLeftpt.z = float.Parse(childDict["NearTopLeftZ"]); Point3D topRightpt = new Point3D(); topRightpt.x = float.Parse(childDict["NearTopRightX"]); topRightpt.y = float.Parse(childDict["NearTopRightY"]); topRightpt.z = float.Parse(childDict["NearTopRightZ"]); Point3D bottomLeftpt = new Point3D(); bottomLeftpt.x = float.Parse(childDict["NearBottomLeftX"]); bottomLeftpt.y = float.Parse(childDict["NearBottomLeftY"]); bottomLeftpt.z = float.Parse(childDict["NearBottomLeftZ"]); Point3D bottomRightpt = new Point3D(); bottomRightpt.x = float.Parse(childDict["NearBottomRightX"]); bottomRightpt.y = float.Parse(childDict["NearBottomRightY"]); bottomRightpt.z = float.Parse(childDict["NearBottomRightZ"]); DebugTxt.Text += " topLeftpt.x: " + topLeftpt.x + " topLeftpt.y: " + topLeftpt.y + " topLeftpt.z: " + topLeftpt.z + " " + " topRightpt.x: " + topRightpt.x + " topRightpt.y: " + topRightpt.y + " topRightpt.z: " + topRightpt.z + " " + " bottomLeftpt.x: " + bottomLeftpt.x + " bottomLeftpt.y: " + bottomLeftpt.y + " bottomLeftpt.z: " + bottomLeftpt.z + " " + " bottomRightpt.x: " + bottomRightpt.x + " bottomRightpt.y: " + bottomRightpt.y + " bottomRightpt.z: " + bottomRightpt.z; HoloPoints.Instance.topLeftpt = topLeftpt; HoloPoints.Instance.topRightpt = topRightpt; HoloPoints.Instance.bottomLeftpt = bottomLeftpt; HoloPoints.Instance.bottomRightpt = bottomRightpt; Windows.Web.Http.HttpResponseMessage response = await httpClient.DeleteAsync(uri); } catch (Exception ex) { WebServiceTxt.Text = ex.Message; } } }
public static async Task <bool> CookiedGetReward(string queryId) { if (isCookieValid == false) { await ShowMessageDialog("领取功能需要设置Cookie", "领取操作不仅需要悬赏令ID, 还需要您的BDUSS. 请先设置Cookie."); return(false); } HttpResponseMessage response = null; try { string url = "https://jingyan.baidu.com/patchapi/claimQuery?queryId=" + queryId + "&token=" + newMainBdStoken + "×tamp=" + newMainBdstt; HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)); req.Headers.Referer = new Uri("https://jingyan.baidu.com/patch"); // ----- not working ----- //KeyValuePair<string, string>[] urlParams = { // new KeyValuePair<string, string>("queryId", queryId), // new KeyValuePair<string, string>("token", newMainBdStoken), // new KeyValuePair<string, string>("timestamp", newMainBdstt) //}; //req.Content = new FormUrlEncodedContent(urlParams) as IHttpContent; response = await client.SendRequestAsync(req); string respstr = response.Content.ToString().Replace(" ", ""); bool isGetSucceed = false; if (respstr.IndexOf("\"errno\":0") >= 0) { respstr = "成功领取。请在 个人中心->悬赏经验->已领取 查看。"; isGetSucceed = true; } else if (respstr.IndexOf("\"errno\":302") >= 0) { respstr = "你可能已经领取过经验。领取不成功(302)。"; //isGetSucceed = true; } else if (respstr.IndexOf("\"errno\":2") >= 0) { respstr = "身份验证失败,如果确定Cookie设定有效,可告知开发者 wang1223989563。错误码:2"; } else { respstr = "未知错误类型 (非302或2错误。可告知开发者 wang1223989563) \n错误信息: " + respstr; } await ShowMessageDialog("领取结果", respstr); req.Dispose(); return(isGetSucceed); } catch (COMException e) { await ShowDetailedError("领取未成功", e); return(false); } }
private async void signin_button_Click(object sender, RoutedEventArgs e) { if (signin_email.Text == "" || signin_pswd.Password == "") { MessageDialog r = new MessageDialog("Please enter email and password."); await r.ShowAsync(); signin_email.Focus(FocusState.Keyboard); } else if (!isValidEmail(signin_email.Text.ToString())) { MessageDialog r = new MessageDialog("Invalid email !"); await r.ShowAsync(); signin_email.Focus(FocusState.Keyboard); } else { //System.Net.Http.HttpClient clt = new System.Net.Http.HttpClient(); Dictionary <string, string> pairs = new Dictionary <string, string>(); pairs.Add("email", signin_email.Text); pairs.Add("password", signin_pswd.Password); 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/login.php?" + DateTime.Now), formContent); Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(new Uri("http://158.69.222.199/login.php?" + DateTime.Now), formContent); // MessageDialog r1 = new MessageDialog(response.Content.ToString()); //await r1.ShowAsync(); if (response.Content.ToString().Equals("Connection failed")) { MessageDialog r = new MessageDialog("Unable to connect to the internet."); await r.ShowAsync(); } else if (!response.Content.ToString().Equals("check")) { user_name = response.Content.ToString(); Frame.Navigate(typeof(user_Page), user_name); HttpClient clt = new HttpClient(); string msg = await clt.GetStringAsync(new Uri("http://158.69.222.199/reminder.php?" + DateTime.Now)); if (msg.Equals("skin")) { ShowToast(); } } else if (response.Content.ToString().Equals("check")) { MessageDialog r = new MessageDialog("Email or password incorrect !"); await r.ShowAsync(); } } }
private async void postData(byte[] TempData) { string url = "http://w.dlut.edu.cn/cgi-bin/srun_portal"; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); HttpBufferContent buffer = new HttpBufferContent(TempData.AsBuffer()); Windows.Web.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), buffer).AsTask(cts.Token); this.loginresponse = await response.Content.ReadAsStringAsync().AsTask(cts.Token); }
public async void postXMLData1() { string uri = "http://111.93.131.112/biws/buswebservice"; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); //string stringXml = "<soapenv:Envelope xmlns:com=\"com.busindia.webservices\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body><com:GetPlaceList xmls =\"\"><arg0><franchUserID>?</franchUserID><password>biteam</password><userID>474</userID><userKey>?</userKey><userName>[email protected]</userName><userRole>?</userRole><userStatus>?</userStatus><userType>101</userType></arg0></com:GetPlaceList></soapenv:Body></soapenv:Envelope>"; string franchUserID = "?"; string password = "******"; int userID = 474; string userKey = "?"; string username = "******"; string userRole = "?"; string userStatus = "?"; int usertype = 101; WebServiceClassLiberary.Class1 listings = new WebServiceClassLiberary.Class1(); XDocument element = listings.getList(franchUserID, password, userID, userKey, username, userRole, userStatus, usertype); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = "biwstest:biwstest"; 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 sdata = loadedData.Descendants("PlaceList"). Select(x => new PlaceList { PlaceID = x.Element("placeID").Value, PlaceCode = x.Element("placeCode").Value, PlaceName = x.Element("placeName").Value }); foreach (var item in sdata) { PlaceList pl = new PlaceList(); pl.PlaceID = item.PlaceID; pl.PlaceName = item.PlaceName; pl.PlaceCode = item.PlaceCode; CityList.Add(pl); } ListMenuItems.ItemsSource = sdata; }
// TODO: Come back to these when we find a better logging library/implementation private async Task LogHttpFailure(HttpResponseMessage response, [CallerMemberName] string callerMethod = "Unknown Method") { if (response.Content != null) { //string errorResponse = await response.Content?.ReadAsStringAsync(); //_logger.Error( // $"{callerMethod} call failed. Response failed: Error code: {response.StatusCode}. Response message:\n{errorResponse}"); } else { //_logger.Error($"{callerMethod} call failed: Error code: {response.StatusCode}. Did not receive a response message."); } }
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 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 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; } }