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(); } } } }
/// <summary>Gets the covers related to games asynchronous.</summary> /// <param name="games">The games.</param> /// <returns></returns> public async Task <GameRoot[]> GetCoversToGamesAsync(GameRoot[] games) { try { var results = await _httpClient.PostAsync(new Uri(BaseUriString.IGDBCovers), new HttpStringContent( "fields *;" + "where id = (" + IdStringBuilder.GameIds(games) + ");", UnicodeEncoding.Utf8, "application/json")); var jsonGame = await results.Content.ReadAsStringAsync(); var coversArr = JsonConvert.DeserializeObject <GameCover[]>(jsonGame); foreach (var cover in coversArr) { cover.url = "https:" + cover.url; foreach (var game in games) { if (cover.id == game.Cover) { game.GameCover = cover; } } } return(games); } catch (HttpRequestException e) { GrToast.SmallToast(GrToast.Errors.IgdbError); await Log.WriteMessage(this + " ; " + e.Message + " : " + e.StackTrace).ConfigureAwait(true); return(null); } }
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(""); }
/// <summary> /// 登陆 提交验证码 用户名 和 密码 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void dengluClic(object sender, RoutedEventArgs e) { string randCode = ""; foreach (JYSelectImage ii in selectImageArr) { randCode += ((int)ii.nowSelect.X + "," + ((int)ii.nowSelect.Y - 30) + ","); } if (randCode == "") { MessageDialog messagedia = new MessageDialog("请注意必须选择验证码"); messagedia.ShowAsync(); return; } if (textBoxName.Text.ToString().Length == 0 || textBoxName.Text.ToString().Length == 0) { MessageDialog messagedia = new MessageDialog("用户名或密码不能为空"); messagedia.ShowAsync(); return; } randCode = randCode.Remove(randCode.Length - 1, 1); Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("randCode", randCode); dic.Add("rand", "sjrand"); var content = new HttpFormUrlEncodedContent(dic); Uri uri = new Uri("https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn"); HttpResponseMessage message = await client.PostAsync(uri, content); if (message.StatusCode == HttpStatusCode.Ok && message != null) { JsonObject json = JsonObject.Parse(message.Content.ToString()); JsonObject data = json["data"].GetObject(); int result = int.Parse(data["result"].GetString()); if (result == 1) { beginLogin(); } else { MessageDialog me = new MessageDialog("验证码错误,请重新尝试"); me.ShowAsync(); closImages(); initGetImage(); } } }
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 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> 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(""); }
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(); }
/// <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 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); }
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 }
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 <MovementResponseDto> PostMovement(string cardId) { MovementResponseDto result = null; //TODO move to config var deviceId = 4; var uriBuilder = new UriBuilder(ApiBaseUrl) { Path = "api/Movement" }; try { //Send the POST request var movementDto = new MovementDto { Uid = cardId, DeviceId = deviceId, SwipeTime = DateTime.UtcNow }; var postBody = JsonConvert.SerializeObject(movementDto); var httpResponse = await _httpClient.PostAsync(uriBuilder.Uri, new HttpStringContent(postBody, UnicodeEncoding.Utf8, "application/json")); if (!httpResponse.IsSuccessStatusCode) { return(null); } var httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); //guarded parse if (string.IsNullOrEmpty(httpResponseBody)) { return(null); } result = JsonConvert.DeserializeObject <MovementResponseDto>(httpResponseBody); 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 static async Task <bool> GetAccessTokenAsync(OAuthModel OAuth) { string URL = OAuth.OAuthBaseUri + "client_id=" + OAuth.clientId + "&response_type=code&redirect_uri=" + OAuth.redirectUri; Uri requireUri = new Uri(URL); Uri callbackUri = new Uri(OAuth.redirectUri); WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requireUri, callbackUri); switch (result.ResponseStatus) { case WebAuthenticationStatus.Success: Debug.WriteLine("success"); string responseData = result.ResponseData; string[] Data = responseData.Split('='); OAuth.code = Data[1]; string tokenUrl = "https://api.weibo.com/oauth2/access_token?client_id=" + OAuth.clientId + "&client_secret=" + OAuth.client_secret + "&grant_type=authorization_code&redirect_uri=" + OAuth.redirectUri + "&code=" + OAuth.code; Uri tokenUri = new Uri(tokenUrl); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var response = await httpClient.PostAsync(tokenUri, new HttpStringContent("")); Debug.WriteLine(response.Content); if (response.IsSuccessStatusCode) { var responseResult = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseResult); var splitString = responseResult.Split(new string[] { "{\"", "\",\"", "\":\"", "\":", ",\"", "\"}" }, StringSplitOptions.RemoveEmptyEntries); Debug.WriteLine(splitString.ToString()); OAuth.access_token = splitString[1]; OAuth.remind_in = splitString[3]; OAuth.expires_in = int.Parse(splitString[5]); OAuth.uid = Int64.Parse(splitString[7]); OAuth.isRealName = bool.Parse(splitString[9]); ApplicationData.Current.LocalSettings.Values["AccessToken"] = OAuth.access_token; ApplicationData.Current.LocalSettings.Values["uid"] = OAuth.uid; //{"access_token":"2.004hKTODJy_fJCc62c96775c1D7OkD","remind_in":"157679999","expires_in":157679999,"uid":"2962219841","isRealName":"true"} return(true); } else { await new MessageDialog("There is an error to get the Authorization").ShowAsync(); } break; case WebAuthenticationStatus.ErrorHttp: Debug.WriteLine("Error http"); await new MessageDialog("Error http").ShowAsync(); break; case WebAuthenticationStatus.UserCancel: Debug.WriteLine("User cancel"); await new MessageDialog("User cancel").ShowAsync(); break; } return(false); }
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); }
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(); } } }
public async Task <HttpResponseMessage> PostUrlAsync(string url, string body) { 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); HttpStringContent stringBody = new HttpStringContent(body, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), stringBody); return(response); }
public static async Task <bool> AddQuizToDbAsync(Quiz quiz) { var json = JsonConvert.SerializeObject(quiz, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var result = await httpClient.PostAsync(quizzesBaseUri, new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); return(result.IsSuccessStatusCode); }
public async void LoadCabinMember(CabinCrewLogin cabinCrewLogin) { var cabinCrewJson = JsonConvert.SerializeObject(cabinCrewLogin); Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(); var res = await client.PostAsync(new Uri("http://localhost:5000/api/User/cabincrew/login"), new HttpStringContent(cabinCrewJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); if (res.IsSuccessStatusCode) { Model.CabinCrew cr = JsonConvert.DeserializeObject <Model.CabinCrew>(res.Content.ToString()); if (cr != null) { Flight = cr.Flight; } } }
/// <summary> /// 上传图片 /// </summary> public async void UpLoad() { string url = "https://sm.ms/api/upload"; HttpClient webHttpClient = new HttpClient(); HttpMultipartFormDataContent httpMultipartFormDataContent = new HttpMultipartFormDataContent(); var fileContent = new HttpStreamContent(await File.OpenAsync(FileAccessMode.Read)); fileContent.Headers.Add("Content-Type", "application/octet-stream"); httpMultipartFormDataContent.Add(fileContent, "smfile", File.Name); var str = await webHttpClient.PostAsync(new Uri(url), httpMultipartFormDataContent); ResponseString = str.Content.ToString(); OnUploadedEventHandler?.Invoke(this, ResponseString); }
/// <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; } }
// Add A Task WITH Parameters public async System.Threading.Tasks.Task AddNewTask(string description) { var task = new Task() { Description = description, DoneTask = false }; var taskJson = JsonConvert.SerializeObject(task); HttpClient httpClient = new HttpClient(); var res = await httpClient.PostAsync(new Uri("http://localhost:5001/api/Task"), new HttpStringContent(taskJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); if (res.IsSuccessStatusCode) { Tasks.Add(JsonConvert.DeserializeObject <Task>(res.Content.ToString())); } }
public async Task <BasicWebReport> PostAsync(string url, List <KeyValuePair <string, string> > formData) { BasicWebReport httpReport = new BasicWebReport(); try { var content = new HttpFormUrlEncodedContent(formData); var responseMessage = await _httpClient.PostAsync(new Uri(url), content); httpReport = await CreateHttpReport(responseMessage); } catch (Exception exception) { httpReport.ErrorMessage = GetErrorMessageFromWebException(exception); } return(httpReport); }
public async System.Threading.Tasks.Task AddNewTravellist(Travellist tl /*, string country, string street, string houseNr, DateTime? dateLeave, DateTime? dateBack*/) { //var travellist = new Travellist() { Name = name, Country = country, Street = street, HouseNr = houseNr, DateLeave = dateLeave, DateBack = dateBack }; var test = new Travellist() { Name = tl.Name, Country = tl.Country, Street = "street", HouseNr = "nr", DateLeave = tl.DateLeave, DateBack = tl.DateBack }; var travellistJson = JsonConvert.SerializeObject(test); HttpClient httpClient = new HttpClient(); var res = await httpClient.PostAsync(new Uri("http://localhost:5001/api/Travellist"), new HttpStringContent(travellistJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); if (res.IsSuccessStatusCode) { Travellists.Add(JsonConvert.DeserializeObject <Travellist>(res.Content.ToString())); } }
/// <summary> /// POST for all events sent to the Alexa Voice Service using the events path /// Refer ro : https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/docs/avs-http2-requests /// </summary> /// <returns></returns> public async Task CreatePOSTConnection() { Windows.Web.Http.HttpClient post = new Windows.Web.Http.HttpClient(); post.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", Ini.access_token); post.DefaultRequestHeaders.Add("Keep-Alive", "true"); var content = new Windows.Web.Http.HttpMultipartFormDataContent(); string json = "{\"event\":{\"header\":{\"namespace\":\"System\",\"name\":\"SynchronizeState\",\"messageId\":\"fakeMessageID\"},\"payload\":{}}}"; var stringContent = new Windows.Web.Http.HttpStringContent(json); stringContent.Headers.Add("Content-Disposition", "form-data; name=\"metadata\""); content.Add(stringContent, "metadata"); Debug.WriteLine("Confirm just before POST"); var response = await(post.PostAsync(eventsURL, content)); }
public async System.Threading.Tasks.Task AddNewCat(string name) { var cat = new Category() { Name = name, DoneCat = false, Items = new List <Item>() }; var catJson = JsonConvert.SerializeObject(cat); HttpClient httpClient = new HttpClient(); var res = await httpClient.PostAsync(new Uri("http://localhost:5001/api/Category/"), new HttpStringContent(catJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); if (res.IsSuccessStatusCode) { Category newCat = JsonConvert.DeserializeObject <Category>(res.Content.ToString()); Categories.Add(newCat); Travellist.Categories.Add(newCat); CategoryNames.Add(newCat.Name); } }
/// <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; } }
/// <summary> /// Posts a JSON object as a string, uses JObject from Newtonsoft.Json 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 Newtonsoft Jobject to post tp the address</param> internal override string PostJson(string location, JObject arguments) { string strResponseValue = string.Empty; Debug.WriteLine("This was searched:"); Debug.WriteLine(EndPoint + location + "?apikey=" + ApiKey); String argumentString = string.Empty; argumentString = JsonConvert.SerializeObject(arguments); //var content = new StringContent(arguments.ToString(), Encoding.UTF8, "application/json"); //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); //headers.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("application/json")); 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(argumentString, UnicodeEncoding.Utf8, "application/json"); //arg.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //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); }
// Add A Item WITH Parameters public async System.Threading.Tasks.Task AddNewItem(string name, int amount, string catName) { var item = new Item() { Name = name, Amount = amount, DoneItem = false }; var categoryId = Categories.Where(c => c.Name.Equals(catName)).FirstOrDefault().Id; var itemJson = JsonConvert.SerializeObject(item); HttpClient httpClient = new HttpClient(); var res = await httpClient.PostAsync(new Uri("http://localhost:5001/api/Category/" + categoryId + "/NewItem"), new HttpStringContent(itemJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")); if (res.IsSuccessStatusCode) { Category cat = Categories.Where(c => c.Id == categoryId).FirstOrDefault(); cat.Items.Add(JsonConvert.DeserializeObject <Item>(res.Content.ToString())); List <Item> orderdItems = cat.Items.OrderBy(i => i.Name).ToList(); cat.Items = orderdItems; } }
private async void Upload_Click(object sender, RoutedEventArgs e) { FileOpenPicker open = new FileOpenPicker(); open.SuggestedStartLocation = PickerLocationId.PicturesLibrary; open.ViewMode = PickerViewMode.Thumbnail; // Filter to include a sample subset of file types open.FileTypeFilter.Clear(); open.FileTypeFilter.Add(".bmp"); open.FileTypeFilter.Add(".png"); open.FileTypeFilter.Add(".jpeg"); open.FileTypeFilter.Add(".jpg"); // Open a stream for the selected file StorageFile file = await open.PickSingleFileAsync(); // Ensure a file was selected if (file != null) { // Ensure the stream is disposed once the image is loaded using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) { BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(fileStream); fileStream.AsStream().CopyTo(stream); //img.Source = bitmapImage; } } Uri uri = new Uri(serverAddressField.Text); Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri); request.Content = streamContent; Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, streamContent).AsTask(cts.Token); }
private async void send(object sender, RoutedEventArgs e) { progressbar.Text = "Sending contribution"; progressbar.ShowAsync(); var client = new Windows.Web.Http.HttpClient(); Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; if (!localSettings.Containers.ContainsKey("userInfo")) { MessageDialog msgbox = new MessageDialog("Please log-in first. Go to settings from the main menu."); await msgbox.ShowAsync(); progressbar.HideAsync(); Frame.Navigate(typeof(Settings)); return; } var username = localSettings.Containers["userInfo"].Values["userName"].ToString(); HttpStringContent content = new HttpStringContent( "{ \"Username\": \"" + username + "\", \"Category\": \"" + category_box.Text + "\", \"Title\": \"" + title_box.Text + "\", \"Content\": \"" + content_box.Text + "\", \"AdditionalContent\": \"" + add_box.Text + "\" }", UnicodeEncoding.Utf8, "application/json"); Debug.WriteLine(content); var uri = new Uri("http://codeinn-acecoders.rhcloud.com:8000/contribute"); var response = await client.PostAsync(uri, content); var result = await response.Content.ReadAsStringAsync(); MessageDialog msgbox1 = new MessageDialog(result + " Thanks a lot!"); await msgbox1.ShowAsync(); progressbar.HideAsync(); }
public virtual async Task <string> post(Uri link, IHttpContent content) { var cts = new CancellationTokenSource(); cts.CancelAfter(1000); try { var response = await client.PostAsync(link, content); if (response == null || !response.IsSuccessStatusCode) { return(null); } string jsonResponse = await response.Content.ReadAsStringAsync(); return(jsonResponse); } catch (Exception) { return(null); } }
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 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 } }
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 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; }
public async void sendInstruction(Item item, String newState) { if (localSettings.Values["connectionType"] != null) { if (localSettings.Values["connectionType"].ToString().Equals(ConnectionTypesEnum.HTTPSwithUsernameAndPassword.ToString())) { filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired); filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName); filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.IncompleteChain); filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential("https", localSettings.Values["username"].ToString(), passwordVault.Retrieve("winHAB", localSettings.Values["username"].ToString()).Password); httpClient = new Windows.Web.Http.HttpClient(filter); String method = newState; UTF8Encoding encoder = new UTF8Encoding(); Byte[] bytes = encoder.GetBytes(method); UriBuilder uri = new UriBuilder(item.link); try { HttpResponseMessage response = await httpClient.PostAsync(uri.Uri, new HttpStringContent(method)); } catch (Exception ex) { //MessageDialog dialog = new MessageDialog(ex.Message + "\n" + ex.StackTrace, "Error while sending a request"); //dialog.Options = MessageDialogOptions.AcceptUserInputAfterDelay; //dialog.ShowAsync(); ErrorLogger.printErrorToLog(ex.Message, ex.StackTrace); } finally { } } if (localSettings.Values["connectionType"].ToString().Equals(ConnectionTypesEnum.HTTPSwithoutUsernameAndPassword.ToString())) { filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired); filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName); filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.IncompleteChain); httpClient = new Windows.Web.Http.HttpClient(filter); String method = newState; UTF8Encoding encoder = new UTF8Encoding(); Byte[] bytes = encoder.GetBytes(method); try { UriBuilder uri = new UriBuilder(item.link); HttpResponseMessage response = await httpClient.PostAsync(uri.Uri, new HttpStringContent(method)); } catch (Exception ex) { //MessageDialog dialog = new MessageDialog(ex.Message + "\n" + ex.StackTrace, "Error while sending a request"); //dialog.Options = MessageDialogOptions.AcceptUserInputAfterDelay; //dialog.ShowAsync(); ErrorLogger.printErrorToLog(ex.Message, ex.StackTrace); } finally { } } if (localSettings.Values["connectionType"].ToString().Equals(ConnectionTypesEnum.HTTPwithUsernameAndPassword.ToString())) { filter.ServerCredential = new PasswordCredential("winHAB", localSettings.Values["username"].ToString(), passwordVault.Retrieve("winHAB", localSettings.Values["username"].ToString()).Password); httpClient = new HttpClient(filter); String method = newState; UTF8Encoding encoder = new UTF8Encoding(); Byte[] bytes = encoder.GetBytes(method); try { UriBuilder uri = new UriBuilder(item.link); HttpResponseMessage response = await httpClient.PostAsync(uri.Uri, new HttpStringContent(method)); } catch (Exception ex) { //MessageDialog dialog = new MessageDialog(ex.Message + "\n" + ex.StackTrace, "Error while sending a request"); //dialog.Options = MessageDialogOptions.AcceptUserInputAfterDelay; //dialog.ShowAsync(); ErrorLogger.printErrorToLog(ex.Message, ex.StackTrace); } finally { } } if (localSettings.Values["connectionType"].ToString().Equals(ConnectionTypesEnum.HTTPwithoutUsernameAndPassword.ToString())) { httpClient = new Windows.Web.Http.HttpClient(); String method = newState; UTF8Encoding encoder = new UTF8Encoding(); Byte[] bytes = encoder.GetBytes(method); try { UriBuilder uri = new UriBuilder(item.link); HttpResponseMessage response = await httpClient.PostAsync(uri.Uri, new HttpStringContent(method)); } catch (Exception ex) { //MessageDialog dialog = new MessageDialog(ex.Message + "\n" + ex.StackTrace, "Error while sending a request"); //dialog.Options = MessageDialogOptions.AcceptUserInputAfterDelay; //dialog.ShowAsync(); ErrorLogger.printErrorToLog(ex.Message, ex.StackTrace); } finally { } } } }