コード例 #1
1
        private async Task Authorize(string code)
        {
            Uri uri = new Uri("https://api.weibo.com/oauth2/access_token");

            List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();

            pairs.Add(new KeyValuePair<string, string>("client_id", appInfo.Key));
            pairs.Add(new KeyValuePair<string, string>("client_secret", appInfo.Secret));
            pairs.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
            pairs.Add(new KeyValuePair<string, string>("code", code));
            pairs.Add(new KeyValuePair<string, string>("redirect_uri", appInfo.RedirectUri));

            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(pairs);

            using (HttpClient client = new HttpClient())
            {
                DateTime time = DateTime.Now;

                HttpResponseMessage response;
                try
                {
                    response = await client.PostAsync(uri, content);
                }
                catch (Exception ex)
                {
                    throw new Exception("network error", ex);
                }
                string json = await response.Content.ReadAsStringAsync();

                JObject accessToken = JsonConvert.DeserializeObject<JObject>(json);
                UserInfo.Token = accessToken["access_token"].ToString();
                UserInfo.ExpiresAt = Untils.ToTimestamp(time) + (long)accessToken["expires_in"];
                UserInfo.Uid = accessToken["uid"].ToString();
            }
        }
コード例 #2
0
ファイル: CoreApi.cs プロジェクト: areglos/Cafeine
        public static async Task <bool> Authentication(string port, string username, string password)
        {
            Uri uri = new Uri("http://localhost:" + port + "/login");

            //try {
            using (var client = new HttpClient()) {
                Dictionary <string, string> authentication = new Dictionary <string, string>();
                authentication.Add("username", username);
                authentication.Add("password", password);

                HttpFormUrlEncodedContent x = new HttpFormUrlEncodedContent(authentication);
                var result = client.PostAsync(uri, x).GetAwaiter().GetResult();
                result.EnsureSuccessStatusCode();
                result.Dispose();
                //store user credential and port
                var vault = new PasswordVault();
                var cred  = new PasswordCredential("qBittorent", username, password);
                vault.Add(cred);
                ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                localSettings.Values["localport"] = port;
                //GC.Collect();
            }
            return(await Task.FromResult(true));

            //}
            //catch(Exception e) {

            //}
        }
コード例 #3
0
        /// <summary>
        /// Method which connects to the Iliad personal area of the user and then
        /// reads the HTML code of the web page to get the details about costs
        /// and consumes.
        /// </summary>
        /// <param name="username">The username of the account</param>
        /// <param name="password">The password of the account</param>
        /// <returns></returns>
        public async Task Authenticate(string username, string password)
        {
            _client.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

            await _client.GetAsync(new Uri(Resources.GetString("LoginURL")));

            _POSTData = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("login-ident", username),
                new KeyValuePair <string, string>("login-pwd", password)
            });

            HttpResponseMessage response = await _client.PostAsync(new Uri(Resources.GetString("LoginURL")), _POSTData);

            response.EnsureSuccessStatusCode();

            HtmlDocument document = new HtmlDocument()
            {
                OptionFixNestedTags = true
            };

            document.LoadHtml((await response.Content.ReadAsStringAsync()));

            ReadConsumes(document);
        }
コード例 #4
0
        public static async void HttpPost(string phone, string password)
        {
            try
            {
                HttpClient httpClient = new HttpClient();
                string     posturi    = Config.apiUserRegister;

                string                    date     = DateTime.Now.Date.Year.ToString() + "-" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Day.ToString();
                HttpRequestMessage        request  = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
                HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
                    new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("phone", phone),       //手机号
                    new KeyValuePair <string, string>("password", password), //密码
                    new KeyValuePair <string, string>("date", date),         //注册日期
                }
                    );
                request.Content = postData;
                HttpResponseMessage response = await httpClient.SendRequestAsync(request);

                string responseString = await response.Content.ReadAsStringAsync();



                JsonObject register = JsonObject.Parse(responseString);
                try
                {
                    int code = (int)register.GetNamedNumber("code");
                    switch (code)
                    {
                    case 0:
                    {
                        JsonObject user = register.GetNamedObject("user");
                        Config.UserPhone = user.GetNamedString("phone");
                        NavigationHelp.NavigateTo(typeof(UserData));
                        break;
                    }

                    case 1:
                        HelpMethods.Msg("手机号已注册!");
                        break;

                    case 2:
                        HelpMethods.Msg("未知错误!");
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    HelpMethods.Msg(ex.Message.ToString());
                }
            }
            catch (Exception ex)
            {
                HelpMethods.Msg(ex.Message.ToString());
            }
        }
コード例 #5
0
ファイル: VehicleDetails.xaml.cs プロジェクト: kleitz/WPApp
        private async void updateVehicleInfo(string type, string motorplate, string reg_certificate)
        {
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("type", type);
            postData.Add("license_plate", motorplate);
            postData.Add("reg_certificate", reg_certificate);

            postData.Add("vehicle_img", ImageConvert.ImageConvert.convertImageToBase64(imgVehicle));
            postData.Add("license_plate_img", ImageConvert.ImageConvert.convertImageToBase64(imgLicensePlate));
            postData.Add("motor_insurance_img", ImageConvert.ImageConvert.convertImageToBase64(imgMotorInsurance));

            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);

            var result = await RequestToServer.sendPutRequest("vehicle/" + Global.GlobalData.selectedVehicle.vehicle_id, content);

            JObject jsonObject = JObject.Parse(result);
            if (jsonObject.Value<bool>("error"))
            {
                MessageBox.Show(jsonObject.Value<string>("message"));
            }
            else
            {
                //Global.GlobalData.isDriver = true;
                MessageBox.Show(jsonObject.Value<string>("message"));
                // refresh lai trang
                NavigationService.Navigate(new Uri("/Refresh.xaml", UriKind.RelativeOrAbsolute));
            }

        }       
コード例 #6
0
        private async Task<string> GetTokenFromAzureOAuthAsync()
        {
            var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>
            {
                { "grant_type", "client_credentials" },
                { "client_id", clientId },
                { "client_secret", clientSecret },
                { "resource", appIdUri },
            });
            content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage result = await client.PostAsync(
                    new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/token"), content);

                string responseString = await result.Content.ReadAsStringAsync();
                JsonValue response = JsonValue.Parse(responseString);

                return response.GetObject().GetNamedString("access_token");
            }
            catch (Exception ex)
            {
                // Networking errors in PostAsync are reported as exceptions.
                // JSON parsing errors are also reported as exceptions.
                Output.Text = $"Failed to load Azure OAuth Token: {ex}";
                return String.Empty;
            }
        }
コード例 #7
0
ファイル: HttpPostRegister.cs プロジェクト: x01673/dreaming
       public static async void HttpPost(string phone, string password)
       {
           try
           {

               HttpClient httpClient = new HttpClient();
               string posturi = Config.apiUserRegister;

               string date = DateTime.Now.Date.Year.ToString() + "-" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Day.ToString();
               HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
               HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
                   new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("phone", phone),//手机号
                        new KeyValuePair<string, string>("password", password),//密码
                        new KeyValuePair<string, string>("date", date),//注册日期
                    }
               );
               request.Content = postData;
               HttpResponseMessage response = await httpClient.SendRequestAsync(request);
               string responseString = await response.Content.ReadAsStringAsync();
             


               JsonObject register = JsonObject.Parse(responseString);
               try
               {
                   int code = (int)register.GetNamedNumber("code");
                   switch (code)
                   {
                       case 0:
                           {
                               JsonObject user = register.GetNamedObject("user");
                               Config.UserPhone = user.GetNamedString("phone");
                               NavigationHelp.NavigateTo(typeof(UserData));
                               break;
                           }
                       case 1:
                           HelpMethods.Msg("手机号已注册!");
                           break;
                       case 2:
                           HelpMethods.Msg("未知错误!");
                           break;
                       default:
                           break;

                   }
               }
               catch (Exception ex)
               {
                   HelpMethods.Msg(ex.Message.ToString());
               }
               

           }
           catch (Exception ex)
           {
               HelpMethods.Msg(ex.Message.ToString());
           }
       }
コード例 #8
0
       public static async void HttpPost(string cid, string cname, string cimage, string cdream, string fid, string fname,string fimage,string fdream)
       {
           try
           {

               HttpClient httpClient = new HttpClient();
               HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(Config.apiUserFollow));
               HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
                   new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("cphone", cid),
                        new KeyValuePair<string, string>("cname", cname),
                        new KeyValuePair<string, string>("cimage", cimage),
                        new KeyValuePair<string, string>("cdream", cdream),
                        new KeyValuePair<string, string>("fphone", fid),
                        new KeyValuePair<string, string>("fname", fname),
                        new KeyValuePair<string, string>("fimage", fimage),
                        new KeyValuePair<string, string>("fdream", fdream),
                       
                       
                        
                    }
               );
               request.Content = postData;
               HttpResponseMessage response = await httpClient.SendRequestAsync(request);
               string responseString = await response.Content.ReadAsStringAsync();
              


           }
           catch (Exception ex)
           {
               HelpMethods.Msg(ex.Message.ToString());
           }
       }
コード例 #9
0
        public static async Task <ContentManageResult> RemoveFollowCommunityAsync(NiconicoContext context, string communityId)
        {
            var token = await GetCommunityLeaveTokenAsync(context, communityId);

            var url  = NiconicoUrls.CommunityLeavePageUrl + token.CommunityId;
            var dict = new Dictionary <string, string>();

            dict.Add("time", token.Time);
            dict.Add("commit_key", token.CommitKey);
            dict.Add("commit", token.Commit);

#if WINDOWS_UWP
            var content = new HttpFormUrlEncodedContent(dict);
#else
            var content = new FormUrlEncodedContent(dict);
#endif


            var request = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.Headers.Add("Referer", url);
            request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

            request.Content = content;
            var postResult = await context.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            Debug.WriteLine(postResult);

            return(postResult.IsSuccessStatusCode ? ContentManageResult.Success : ContentManageResult.Failed);
        }
コード例 #10
0
    public async UniTask PostRequestAsync()
    {
#if WINDOWS_UWP
        var content = new HttpFormUrlEncodedContent(new Dictionary <string, string>
        {
            { key, zipcode.ToString() },
        });

        var uri = new Uri(url);

        {
            // ヘッダを付けて、画像(バイナリ)を送信する場合
            //var request = new HttpRequestMessage(HttpMethod.Post, uri);
            //request.Headers.Add("foo", "hoge");
            //var file = await KnownFolders.CameraRoll.GetFileAsync("test.jpg");
            //var buffer = await FileIO.ReadBufferAsync(file);
            //var byteContent = new HttpBufferContent(buffer);
            //byteContent.Headers.Add("Content-Type", "image/jpeg");

            //var data = new HttpMultipartFormDataContent();
            //data.Add(new HttpStringContent(zipcode.ToString()), key);
            //data.Add(byteContent, "file", "test.jpg");
            //request.Content = data;

            //var res = await httpClient.SendRequestAsync(request);
        }

        var response = await httpClient.PostAsync(uri, content);

        var text = await response.Content.ReadAsStringAsync();

        Debug.Log($"post success. {nameof(WindowsHttpClientSamples)}.{nameof(PostRequestAsync)}");
        Debug.Log(text);
#endif
    }
コード例 #11
0
ファイル: Class1.cs プロジェクト: CuiXiaoDao/cnblogs-UAP
        public async void SetupPushNotificationChannelForApplicationAsync(string token, string arguments)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                throw new ArgumentException("you should add you app token");
            }

            //var encryptedArguments = Helper.Encrypt(arguments, "cnblogs", "somesalt");

            _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

            var content = new HttpFormUrlEncodedContent(new[] {
                new KeyValuePair<string, string>("arguments", arguments),
                new KeyValuePair<string, string>("token", token),
                new KeyValuePair<string, string>("uri", _channel.Uri),
                new KeyValuePair<string, string>("uuid", GetUniqueDeviceId())
            });
            var request = new HttpRequestMessage(HttpMethod.Post, new Uri(server));

            request.Content = content;

            var client = new HttpClient();

            var response = await client.SendRequestAsync(request);

            _channel.PushNotificationReceived += _channel_PushNotificationReceived;
        }
コード例 #12
0
        /// <summary>
        /// 模拟登陆
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private static async Task <bool> Login(string username, string password)
        {
            // This is the postdata
            var postData = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("user", username),
                new KeyValuePair <string, string>("pass", password)
            };

            IHttpContent content = new HttpFormUrlEncodedContent(postData);

            HttpResponseMessage message = await App.HttpClient.PostAsync(new Uri("http://neihanshe.cn/login", UriKind.Absolute), content);

            var contentType = message.Content.Headers.ContentType;

            if (contentType != null && string.IsNullOrEmpty(contentType.CharSet))
            {
                contentType.CharSet = "utf-8";
            }
            if (message.Content.ToString().Contains("<li id=\"error_info\">账号或密码不正确!</li>"))
            {
                return(false);
            }
            return(true);
        }
コード例 #13
0
        public async Task <bool> PostAsync(string url, string message, MessageLevel level = MessageLevel.Info)
        {
            // Create an HttpClient and send content payload
            using (var httpClient = HttpClient)
            {
#if __IOS__ || __ANDROID__ || NET45
                var content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "message", message },
                    { "level", level.ToString().ToLower() }
                });
#endif
#if NETFX_CORE
                var content = new HttpFormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "message", message },
                    { "level", level.ToString().ToLower() }
                });
#endif

                var response = await httpClient.PostAsync(new Uri(url), content);

                return(response.IsSuccessStatusCode);
            }
        }
コード例 #14
0
ファイル: MainPage.xaml.cs プロジェクト: onsa440hz/OpenTouryo
        private async void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            using (HttpClient client = new HttpClient())
            {
                string message = string.Empty; // 結果メッセージ

                try
                {
                    if (string.IsNullOrEmpty(this.txtShipperID.Text) || string.IsNullOrEmpty(this.txtCompanyName.Text) || string.IsNullOrEmpty(this.txtPhone.Text))
                    {
                        message = "Shipper Id, Company Name, Phone のいずれかが入力されていません。1件表示の Shipper Id テキストボックスに更新対象の Shipper Id の値を、Compnay Name, Phone テキストボックスに、更新する値をそれぞれ入力してください。";
                        return;
                    }

                    // Web API の URL
                    Uri uri = new Uri("http://localhost:63877/SPA_Sample/api/Update");

                    // Request Header を定義する
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));

                    // Web API に送信するデータを構築する
                    HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(new Dictionary <string, string>
                    {
                        { "ddlDap", ((ComboBoxItem)this.ddlDap.SelectedItem).Tag.ToString() },
                        { "ddlMode1", ((ComboBoxItem)this.ddlMode1.SelectedItem).Tag.ToString() },
                        { "ddlMode2", ((ComboBoxItem)this.ddlMode2.SelectedItem).Tag.ToString() },
                        { "ddlExRollback", ((ComboBoxItem)this.ddlExRollback.SelectedItem).Tag.ToString() },
                        { "ShipperId", this.txtShipperID.Text },
                        { "CompanyName", this.txtCompanyName.Text },
                        { "Phone", this.txtPhone.Text }
                    });

                    HttpResponseMessage response = await client.PostAsync(uri, content);

                    if (response.IsSuccessStatusCode)
                    {
                        // 正常終了
                        string jsonResult = await response.Content.ReadAsStringAsync();

                        Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonResult);
                        message = dic["message"];
                    }
                    else
                    {
                        // エラー終了
                        message = "HTTP Error! Status Code: " + response.StatusCode;
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
                finally
                {
                    // 結果を表示
                    this.txtResult.Text = message;
                }
            }
        }
コード例 #15
0
        private static async Task<Response<string>> GetResponseAsync(string relativeUriFormat, User user)
        {
            Response<string> response;

            try
            {
                string dob = user.DateOfBirth.ToString("ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture);
                var postContent = new HttpFormUrlEncodedContent(
                                    new KeyValuePair<string, string>[3] {
                                        new KeyValuePair<string, string>("regno", user.RegNo),
                                        new KeyValuePair<string, string>("dob", dob),
                                        new KeyValuePair<string, string>("mobile", user.PhoneNo)
                                    });

                string uriString = BASE_URI_STRING + String.Format(relativeUriFormat, user.Campus);
                HttpResponseMessage httpResponse = await _httpClient.PostAsync(new Uri(uriString), postContent);
                response = await GetRootResponseAsync(httpResponse);
            }
            catch
            {
                response = new Response<string>(StatusCode.NoInternet, null);
            }

            return response.Format();
        }
コード例 #16
0
ファイル: HttpPostComment.cs プロジェクト: x01673/dreaming
        public static async void HttpPost(string id,string phone,string image, string name, string content, string time,string atName,string atPhone,string atImage)
        {
            try
            {

                HttpClient httpClient = new HttpClient();
                string posturi = Config.apiCommentPublish;
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
                HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
                    new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string,string>("id",id),
                        new KeyValuePair<string,string>("phone",phone),
                        new KeyValuePair<string, string>("image", image),
                        new KeyValuePair<string, string>("name", name),
                        new KeyValuePair<string, string>("content", content),
                        new KeyValuePair<string, string>("time", time),
                        new KeyValuePair<string, string>("atName", atName),
                        new KeyValuePair<string, string>("atPhone", atPhone),
                        new KeyValuePair<string, string>("atImage", atImage),
                    }
                );
                request.Content = postData;
                HttpResponseMessage response = await httpClient.SendRequestAsync(request);
              }
            catch (Exception ex)
            {
                HelpMethods.Msg(ex.Message.ToString());
            }
        }
コード例 #17
0
ファイル: WebHelper.cs プロジェクト: Orochi4268/Aurora.Music
        public static async Task <string> HttpPostForm(string url, IEnumerable <KeyValuePair <string, string> > form, bool ignoreStatus = false)
        {
            try
            {
                Uri requestUri = new Uri(url);
                var content    = new HttpFormUrlEncodedContent(form);
                using (var response = await httpClient.PostAsync(requestUri, content))
                {
                    if (ignoreStatus)
                    {
                    }
                    else
                    {
                        response.EnsureSuccessStatusCode();
                    }
                    var buffer = await response.Content.ReadAsBufferAsync();

                    var byteArray = buffer.ToArray();
                    return(Encoding.UTF8.GetString(byteArray, 0, byteArray.Length));
                }
            }
            catch (Exception)
            {
                //Could not connect to server
                //Use more specific exception handling, this is just an example
                return(null);
            }
        }
コード例 #18
0
ファイル: AddVehicle.xaml.cs プロジェクト: kleitz/WPApp
        private async void btnAddNewVehicle_Click(object sender, RoutedEventArgs e)
        {
            Dictionary <string, string> postData = new Dictionary <string, string>();

            postData.Add("type", txtbType.Text.Trim());
            postData.Add("license_plate", txtbVehiclePlate.Text.Trim());
            postData.Add("reg_certificate", txtbRegistrationCertificate.Text.Trim());

            postData.Add("vehicle_img", ImageConvert.ImageConvert.convertImageToBase64(imgVehicle));
            postData.Add("license_plate_img", ImageConvert.ImageConvert.convertImageToBase64(imgLicensePlate));
            postData.Add("motor_insurance_img", ImageConvert.ImageConvert.convertImageToBase64(imgMotorInsurance));

            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);

            var result = await RequestToServer.sendPostRequest("vehicle", content);

            JObject jsonObject = JObject.Parse(result);

            if (jsonObject.Value <bool>("error"))
            {
                MessageBox.Show(jsonObject.Value <string>("message"));
            }
            else
            {
                //Global.GlobalData.isDriver = true;
                MessageBox.Show(jsonObject.Value <string>("message"));
                // refresh lai trang
                NavigationService.Navigate(new Uri("/Driver/VehicleManagement.xaml", UriKind.RelativeOrAbsolute));
            }
        }
コード例 #19
0
        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();
                    }
                }

            }
        }
コード例 #20
0
ファイル: VehicleDetails.xaml.cs プロジェクト: kleitz/WPApp
        private async void updateVehicleInfo(string type, string motorplate, string reg_certificate)
        {
            Dictionary <string, string> postData = new Dictionary <string, string>();

            postData.Add("type", type);
            postData.Add("license_plate", motorplate);
            postData.Add("reg_certificate", reg_certificate);

            postData.Add("vehicle_img", ImageConvert.ImageConvert.convertImageToBase64(imgVehicle));
            postData.Add("license_plate_img", ImageConvert.ImageConvert.convertImageToBase64(imgLicensePlate));
            postData.Add("motor_insurance_img", ImageConvert.ImageConvert.convertImageToBase64(imgMotorInsurance));

            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);

            var result = await RequestToServer.sendPutRequest("vehicle/" + Global.GlobalData.selectedVehicle.vehicle_id, content);

            JObject jsonObject = JObject.Parse(result);

            if (jsonObject.Value <bool>("error"))
            {
                MessageBox.Show(jsonObject.Value <string>("message"));
            }
            else
            {
                //Global.GlobalData.isDriver = true;
                MessageBox.Show(jsonObject.Value <string>("message"));
                // refresh lai trang
                NavigationService.Navigate(new Uri("/Refresh.xaml", UriKind.RelativeOrAbsolute));
            }
        }
コード例 #21
0
        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");
            }
        }
コード例 #22
0
ファイル: HttpPostLogin.cs プロジェクト: x01673/dreaming
        public static async void HttpPost(string phone, string password)
        {
            try
            {
                HttpClient httpClient = new HttpClient();
                string posturi = Config.apiUserLogin;
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
                HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
                    new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("phone", phone),//手机
                        new KeyValuePair<string, string>("password", password),//密码
                    }
                );
                request.Content = postData;
                HttpResponseMessage response = await httpClient.SendRequestAsync(request);
                string responseString = await response.Content.ReadAsStringAsync();
                Debug.WriteLine(responseString);

                JsonObject login = JsonObject.Parse(responseString);
                try
                {
                    int code = (int)login.GetNamedNumber("code");
                    switch (code)
                    {
                        case 0:
                            {
                                JsonObject user = login.GetNamedObject("user");
                                Config.UserName = user.GetNamedString("name") ;
                                Config.UserImage = Config.apiFile + user.GetNamedString("image");
                                Config.UserPhone = user.GetNamedString("phone") ;
                                Config.UserDream = user.GetNamedString("dream") ;
                                Config.UserTag = user.GetNamedString("tag");
                                NavigationHelp.NavigateTo(typeof(Main));
                                break;
                            }
                        case 1:
                            HelpMethods.Msg("手机号未注册!");
                            break;
                        case 2:
                            HelpMethods.Msg("密码错误!");
                            break;
                        default:
                            break;

                    }
                }
                catch (Exception ex)
                {
                    HelpMethods.Msg("服务器出错!");
                    Debug.WriteLine(ex.Message.ToString());
                }


            }
            catch (Exception ex)
            {
               HelpMethods.Msg(ex.Message.ToString());
            }
        }
コード例 #23
0
ファイル: HTTPStuff.cs プロジェクト: nidzo732/SecureMessaging
			public async Task<string> SendRequestAsync(string addr, Dictionary<string, string> postargs)
			{

                var content = new HttpFormUrlEncodedContent(postargs);
                string response;
                try
                {
                    var cancelationToken = new CancellationTokenSource();
                    cancelationToken.CancelAfter(100000);
                    var responseObject = (await client.PostAsync(new Uri(Addresses.ADDR_SITE + addr), content).AsTask(cancelationToken.Token));
                    if (!responseObject.IsSuccessStatusCode) throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
                    response = await responseObject.Content.ReadAsStringAsync();
                }
                catch (TimeoutException)
                {
                    throw new SecureMessagingException(Responses.RESPONSE_TIMEOUT);
                }
                catch
                {
                    throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
                }
                if (response==null || response=="")
                {
                    throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
                }
                if (Responses.IsError(response))
                {
                    throw new SecureMessagingException(response);
                }
                return response;
			}
コード例 #24
0
        private async void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            //validate

            //send info to server
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("start_address", txtbStart.Text.Trim());
            postData.Add("end_address", txtbEnd.Text.Trim());
            postData.Add("description", txtbDescription.Text.Trim());
            postData.Add("cost", txtbCost.Text.Trim());
            postData.Add("vehicle_id", txtbVehicleID.Text.Trim());
            postData.Add("distance", txtbDistance.Text.Trim());
            postData.Add("start_address_lat", start_lat.Trim());
            postData.Add("start_address_long", start_long.Trim());
            postData.Add("end_address_lat", end_lat.Trim());
            postData.Add("end_address_long", end_long.Trim());

            string date = datePicker.Value.ToString();
            string time = timePicker.Value.ToString();

            postData.Add("leave_date", "2011-07-07 04:04:04");
            postData.Add("duration", txtbCost.Text.Trim());
            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);

            //var result = await RequestToServer.sendGetRequest("itinerary/2", content);
            var result = await RequestToServer.sendPostRequest("itinerary", content);

            JObject jsonObject = JObject.Parse(result);
            MessageBox.Show(jsonObject.Value<string>("message"));

            //back to trang dau tien

        }
コード例 #25
0
        public static async void HttpPost(string cid, string cname, string cimage, string cdream, string fid, string fname, string fimage, string fdream)
        {
            try
            {
                HttpClient                httpClient = new HttpClient();
                HttpRequestMessage        request    = new HttpRequestMessage(HttpMethod.Post, new Uri(Config.apiUserFollow));
                HttpFormUrlEncodedContent postData   = new HttpFormUrlEncodedContent(
                    new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("cphone", cid),
                    new KeyValuePair <string, string>("cname", cname),
                    new KeyValuePair <string, string>("cimage", cimage),
                    new KeyValuePair <string, string>("cdream", cdream),
                    new KeyValuePair <string, string>("fphone", fid),
                    new KeyValuePair <string, string>("fname", fname),
                    new KeyValuePair <string, string>("fimage", fimage),
                    new KeyValuePair <string, string>("fdream", fdream),
                }
                    );
                request.Content = postData;
                HttpResponseMessage response = await httpClient.SendRequestAsync(request);

                string responseString = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                HelpMethods.Msg(ex.Message.ToString());
            }
        }
コード例 #26
0
ファイル: Task1.cs プロジェクト: Inder18/inderZeroPressure
        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();
        }
コード例 #27
0
ファイル: DataAccess.cs プロジェクト: ChrisBallard/langtutor
 private async Task<bool> Login(string username, string password, bool storeCredentials, bool fromStored)
 {
     var content = new HttpFormUrlEncodedContent(new[]
     {
         new KeyValuePair<string,string>("email", username),
         new KeyValuePair<string, string>("password", password)
     });
     try
     {
         var result = await client.PostAsync(new Uri("http://localhost:8002/api/login"), content);
         if( result.IsSuccessStatusCode )
         {
             if (!fromStored)
             {
                 // interactive login, clear current credentials, and if user wishes to store, do so
                 RemoveStoredCredentials();
                 if (storeCredentials)
                 {
                     var cred = new PasswordCredential(LANGTUTORLOGIN_RES, username, password);
                     passwordVault.Add(cred);
                 }
             }
             return true;
         }
         else
         {
             return false;
         }
     }
     catch(Exception ex)
     {
         return false;
     }
 }
コード例 #28
0
        public IObservable<bool> Post(string url, string message, MessageLevel level = MessageLevel.Info)
        {
            // Create an HttpClient and send content payload
            using (var httpClient = HttpClient)
            {
            #if __IOS__ || __ANDROID__ || NET45
                var content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    {"message", message},
                    {"level", level.ToString().ToLower()}
                });
            #endif
            #if NETFX_CORE
                var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>
                {
                    {"message", message},
                    {"level", level.ToString().ToLower()}
                });
            #endif

            #if __IOS__ || __ANDROID__ || NET45
                return httpClient.PostAsync(new Uri(url), content)
                    .ToObservable()
                    .Select(response => response.IsSuccessStatusCode);
            #endif
            #if NETFX_CORE
                return httpClient.PostAsync(new Uri(url), content)
                    .AsTask()
                    .ToObservable()
                    .Select(response => response.IsSuccessStatusCode);
            #endif
            }
        }
コード例 #29
0
        public async Task UpdateStatus(string status, AdvancedTweet replyToTweet)
        {
            OAuthClient client = new OAuthClient(accessToken);

            try
            {
                using (var content = new HttpFormUrlEncodedContent(new[] { new KeyValuePair <string, string>("status", status) }))
                {
                    var postAddress = "https://api.twitter.com/1.1/statuses/update.json?status=";
                    postAddress += Uri.EscapeUriString(status);
                    if (replyToTweet != null)
                    {
                        postAddress += "&in_reply_to_status_id=" + replyToTweet.tweet.id;
                    }
                    var res = await client.PostAsync(postAddress, null);//TODO: なぜHttpFormUrlEncodedContentが使えないのか調べる

                    if (!res.IsSuccessStatusCode)
                    {
                        var errors = JsonConvert.DeserializeObject <Errors>(res.Content.ToString());
                        throw new Exception("ErrorCode: " + errors.errors[0].code + "\n" + errors.errors[0].message);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(accessToken.screenName + "でツイートできませんでした。", ex);
            }
        }
コード例 #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        private async Task <JObject> CreateHttpRequestAsync(string url, List <KeyValuePair <String, String> > list)//创建http请求 获取Token
        {
            //注:尚未进行断网异常处理
            JObject state = null;

            try
            {
                HttpClient hc = new HttpClient();

                using (var content = new HttpFormUrlEncodedContent(list))
                {
                    var response = await hc.PostAsync(new Uri(url), content);

                    string contentType = response.Content.Headers.ContentType.ToString();
                    var    resdata     = await response.Content.ReadAsStringAsync();

                    JObject result = (JObject)JsonConvert.DeserializeObject(resdata);
                    return(result);
                }
            }
            catch
            {
                return(state);
            }
        }
コード例 #31
0
        private async void receiveButton_Click(object sender, RoutedEventArgs e)
        {
            using (HttpClient client = new HttpClient())
            {
                var input = new Dictionary <string, string>
                {
                    { "email", email },
                };

                var encodedInput = new HttpFormUrlEncodedContent(input);
                //try
                //{
                List <string> tmpList;
                var           resp = await client.PostAsync(new Uri("http://evocreate.tk/retrieveMail.php"), encodedInput);

                if (resp.StatusCode.Equals(HttpStatusCode.NotFound))
                {
                    emailView.ItemsSource = new List <string>()
                    {
                        "No email records found."
                    }
                }
                ;
                else if (resp.StatusCode.Equals(HttpStatusCode.Ok))
                {
                    allEmails = new List <AbsEmailRecord>();
                    string respString = resp.Content.ToString();
                    respString = respString.Replace("<hr/>", "{");
                    respString = respString.Substring(1, respString.Count() - 1);
                    List <string> emailsList = respString.Split('{').ToList();
                    foreach (string s in emailsList)
                    {
                        string snew;
                        snew    = s.Replace("<br/>", "{");
                        tmpList = snew.Split("{".ToCharArray()).ToList();
                        if (tmpList[0] == "noAbsMailUID")
                        {
                            AbsEmailRecord aer = new AbsEmailRecord(tmpList[1], tmpList[2], tmpList[3], tmpList[4], tmpList[5], tmpList[6], false);
                            allEmails.Add(aer);
                        }
                        else
                        {
                            AbsEmailRecord aer = new AbsEmailRecord(tmpList[1], tmpList[2], tmpList[3], tmpList[4], tmpList[5], tmpList[6], true, tmpList[7]);
                            allEmails.Add(aer);
                        }
                    }
                    emailView.ItemsSource = allEmails;
                }
                else
                {
                    DisplayDialog("Error!", "Request timed out!");
                }

                //}
                //catch (Exception)
                //{
                //    DisplayDialog("Error!", "Ensure that you have internet connectivity!");
                //}
            }
        }
コード例 #32
0
        private async Task <HttpResponseMessage> ExecuteCommandUsingRESTApi(string ipAddress, string username, string password, string runCommand, bool isOutputRequired = true)
        {
            var client  = new HttpClient();
            var command = CryptographicBuffer.ConvertStringToBinary(runCommand, BinaryStringEncoding.Utf8);
            var runAsDefaultAccountFalse = CryptographicBuffer.ConvertStringToBinary("false", BinaryStringEncoding.Utf8);
            var timeout = CryptographicBuffer.ConvertStringToBinary(String.Format("{0}", TimeOutAfterNoOutput.TotalMilliseconds), BinaryStringEncoding.Utf8);

            var urlContent = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("command", CryptographicBuffer.EncodeToBase64String(command)),
                new KeyValuePair <string, string>("runasdefaultaccount", CryptographicBuffer.EncodeToBase64String(runAsDefaultAccountFalse)),
                new KeyValuePair <string, string>("timeout", CryptographicBuffer.EncodeToBase64String(timeout)),
            });

            var wdpCommand = isOutputRequired ? WdpRunCommandWithOutputApi : WdpRunCommandApi;
            var uriString  = String.Format("{0}://{1}:{2}{3}?{4}", DefaultProtocol, ipAddress, DefaultPort, wdpCommand, await urlContent.ReadAsStringAsync());
            var uri        = new Uri(uriString);

            var authBuffer = CryptographicBuffer.ConvertStringToBinary(String.Format("{0}:{1}", username, password), BinaryStringEncoding.Utf8);

            client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", CryptographicBuffer.EncodeToBase64String(authBuffer));

            HttpResponseMessage response = await client.PostAsync(uri, null);

            return(response);
        }
コード例 #33
0
        private async void decryptBtn_Click(object sender, RoutedEventArgs e)
        {
            using (HttpClient client = new HttpClient())
            {
                var input = new Dictionary <string, string>
                {
                    { "option", "2" },
                    { "absMailUID", currentEmail.AbsUID }
                };

                var encodedInput = new HttpFormUrlEncodedContent(input);
                try
                {
                    var resp = await client.PostAsync(new Uri("http://evocreate.tk/receivingEndValidation.php"), encodedInput);

                    string symmKey = resp.Content.ToString();
                    currentEmail.EmailContent = Encoding.Unicode.GetString(new AesEnDecryption(symmKey).Decrypt(Encoding.Unicode.GetBytes(currentEmail.EmailContent)));
                    emailTxtBlock.Text        = currentEmail.showFullContent();
                }
                catch (Exception)
                {
                    DisplayDialog("Error", "Ensure that you have internet connectivity!");
                }
            }
        }
コード例 #34
0
ファイル: Upgrade.xaml.cs プロジェクト: kleitz/WPApp
        private async void btnUpgrade_Click(object sender, RoutedEventArgs e)
        {
            //validate all fields

            //upgrade
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("driver_license", txtbDriverLicense.Text.Trim());

            postData.Add("driver_license_img", ImageConvert.ImageConvert.convertImageToBase64(imgDriverLicense));

            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);
            var result = await RequestToServer.sendPostRequest("driver", content);

            JObject jsonObject = JObject.Parse(result);
            if (jsonObject.Value<bool>("error"))
            {
                MessageBox.Show(jsonObject.Value<string>("message"));
            }
            else
            {
                Global.GlobalData.isDriver = true;
                MessageBox.Show(jsonObject.Value<string>("message"));
                // navigate ve acc info
                NavigationService.Navigate(new Uri("/AccountInfo.xaml", UriKind.RelativeOrAbsolute));
            }
            
        }
コード例 #35
0
        public static async Task <string> LogoutAsync()
        {
            Dictionary <string, string> form = new Dictionary <string, string>
            {
                ["action"] = "logout"
            };
            var httpForm = new HttpFormUrlEncodedContent(form);

            HttpResponseMessage httpResponse = new HttpResponseMessage();
            string httpResponseBody          = "";
            var    cancellationTokenSource   = new CancellationTokenSource(1000);

            try
            {
                httpResponse = await httpClient.PostAsync(new Uri(LOGIN_URL), httpForm);
            }
            catch
            {
                return(null);
            }

            if (httpResponse.IsSuccessStatusCode)
            {
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                Debug.WriteLine("NetHelper.LogoutAsync(): " + httpResponseBody);
                return(httpResponseBody);
            }
            else
            {
                return(null);
            }
        }
コード例 #36
0
        private async void integCheckBtn_Click(object sender, RoutedEventArgs e)
        {
            using (HttpClient client = new HttpClient())
            {
                var input = new Dictionary <string, string>
                {
                    { "option", "1" },
                    { "emailHash", getSHA256Hash(currentEmail.EmailContent) },
                    { "absMailUID", currentEmail.AbsUID }
                };

                var encodedInput = new HttpFormUrlEncodedContent(input);
                try
                {
                    var resp = await client.PostAsync(new Uri("http://evocreate.tk/receivingEndValidation.php"), encodedInput);

                    if (resp.StatusCode.Equals(HttpStatusCode.Accepted))
                    {
                        DisplayDialog("Success", "Email content has not been tampered with.");
                    }
                    else
                    {
                        DisplayDialog("Failure", "Email content has been tampered with. Delete it.");
                    }
                }
                catch (Exception)
                {
                    DisplayDialog("Error", "Ensure that you have internet connectivity!");
                }
            }
        }
コード例 #37
0
        private static async Task <string> GetToken(string code, string oauthKey, string oauthSecret)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));

                var content = new HttpFormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("client_id", oauthKey),
                    new KeyValuePair <string, string>("client_secret", oauthSecret),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("redirect_uri", RedirectUrl)
                });

                var response = await httpClient.PostAsync(new Uri("https://api.tvshowtime.com/v1/oauth/access_token"), content);

                var result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(result);
                    throw new ApiException(errorResponse.Message, response.StatusCode);
                }

                string accessToken = JsonConvert.DeserializeObject <AuthenticationResponse>(result).AccessToken;

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    throw new ApiException("The access token retrieved is null or empty.", response.StatusCode);
                }

                return(accessToken);
            }
        }
コード例 #38
0
ファイル: WeiboClient.cs プロジェクト: kimufly/uwp_AiJianShu
        private async Task Authorize(string code)
        {
            Uri uri = new Uri("https://api.weibo.com/oauth2/access_token");

            List <KeyValuePair <string, string> > pairs = new List <KeyValuePair <string, string> >();

            pairs.Add(new KeyValuePair <string, string>("client_id", appInfo.Key));
            pairs.Add(new KeyValuePair <string, string>("client_secret", appInfo.Secret));
            pairs.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
            pairs.Add(new KeyValuePair <string, string>("code", code));
            pairs.Add(new KeyValuePair <string, string>("redirect_uri", appInfo.RedirectUri));

            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(pairs);

            using (HttpClient client = new HttpClient())
            {
                DateTime time = DateTime.Now;

                HttpResponseMessage response;
                try
                {
                    response = await client.PostAsync(uri, content);
                }
                catch (Exception ex)
                {
                    throw new Exception("network error", ex);
                }
                string json = await response.Content.ReadAsStringAsync();

                JObject accessToken = JsonConvert.DeserializeObject <JObject>(json);
                UserInfo.Token     = accessToken["access_token"].ToString();
                UserInfo.ExpiresAt = Untils.ToTimestamp(time) + (long)accessToken["expires_in"];
                UserInfo.Uid       = accessToken["uid"].ToString();
            }
        }
コード例 #39
0
        async public void sendPostHtml(string uriStr, Dictionary <string, string> dic, finishdHtml delegatefi, err e)
        {
            //var content = new HttpFormUrlEncodedContent(dic);
            Uri uri = new Uri(uriStr);

            try
            {
                //CancellationTokenSource cts = new CancellationTokenSource(7000);
                //client.DefaultRequestHeaders.TryAppendWithoutValidation("Accept-Encoding", "gzip, deflate");
                //client.DefaultRequestHeaders.TryAppendWithoutValidation("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
                var content = new HttpFormUrlEncodedContent(dic);
                HttpResponseMessage message = await client.PostAsync(uri, content);

                if (message.StatusCode == HttpStatusCode.Ok && message != null)
                {
                    var contentType = message.Content.Headers.ContentType;
                    if (string.IsNullOrEmpty(contentType.CharSet))
                    {
                        contentType.CharSet = "utf-8";
                    }
                    //  JsonObject json = JsonObject.Parse(message.Content.ToString());

                    delegatefi(message.Content.ToString());
                }
                else
                {
                    e("请求失败");
                }
            }
            catch
            {
                e("链接错误");
            }
        }
コード例 #40
0
        public async Task <Boolean> LoginWithEmail(string username, string password)
        {
            //Login Data
            Dictionary <string, string> dict = new Dictionary <string, string>();

            dict.Add("j_username", username);
            dict.Add("j_password", password);
            IHttpContent content = new HttpFormUrlEncodedContent(dict);

            //Login
            Response resp = await getResponse("http://followshows.com/login/j_spring_security_check", content);

            if (resp.hasInternet && resp.page != null)
            {
                lastPage = resp.page;

                //Check if actually loggedIn
                if (!lastPage.Contains("Wrong email or password."))
                {
                    loggedIn = true;
                    return(true);
                }
            }
            return(false);
        }
コード例 #41
0
        async public void sendPOST(string uriStr, Dictionary <string, string> dic, finishd delegatefi, err e)
        {
            //   Dictionary<string, string> dic = new Dictionary<string, string>();

            var content = new HttpFormUrlEncodedContent(dic);
            Uri uri     = new Uri(uriStr);

            try
            {
                HttpResponseMessage message = await client.PostAsync(uri, content);

                if (message.StatusCode == HttpStatusCode.Ok && message != null)
                {
                    JsonObject json = JsonObject.Parse(message.Content.ToString());

                    delegatefi(json);
                }
                else
                {
                    e("请求失败");
                }
            }
            catch
            {
                e("链接错误");
            }
        }
コード例 #42
0
        /// <summary>
        /// Make a GET request
        /// </summary>
        /// <returns><c>Task&lt;Response&gt;</c></returns>
        public async Task <CXResponse> Get()
        {
            string tempUrl = url;

            if (mHttpContent != null)
            {
                tempUrl += "?" + await mHttpContent.ReadAsStringAsync().AsTask(cts.Token).ConfigureAwait(false);
            }
            else if (rawData != "")
            {
                tempUrl += "?" + rawData;
            }
            else if (data.Count > 0)
            {
                HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(data);
                string p = await content.ReadAsStringAsync().AsTask(cts.Token).ConfigureAwait(false);

                tempUrl += "?" + p;
            }
            Uri uri = new Uri(tempUrl);

            PrepareRequest(uri);
            HttpResponseMessage res = await mHttpClient.GetAsync(uri).AsTask(cts.Token).ConfigureAwait(false);

            return(new CXResponse(res, mFilter.CookieManager.GetCookies(uri)));
        }
コード例 #43
0
 public async Task<string> ExecuteAsync()
 {
     if (OAuthSettings.AccessToken != null)
     {
         return OAuthSettings.AccessToken;
     }
     else if (OAuthSettings.RefreshToken == null)
     {
         return null;
     }
     using (var client = new HttpClient())
     {
         var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>{
                         {"grant_type","refresh_token"},
                         {"refresh_token", OAuthSettings.RefreshToken},
                         {"client_id", OAuthSettings.ClientId},
                         {"client_secret", OAuthSettings.ClientSecret}
                     });
         var response = await client.PostAsync(new Uri(OAuthSettings.TokenEndpoint), content);
         response.EnsureSuccessStatusCode();
         var contentString = await response.Content.ReadAsStringAsync();
         var accessTokenInfo = await JsonConvert.DeserializeObjectAsync<OAuthTokenInfo>(contentString);
         OAuthSettings.AccessToken = accessTokenInfo.AccessToken;
         OAuthSettings.RefreshToken = accessTokenInfo.RefreshToken;
         return OAuthSettings.AccessToken;
     }
 }
コード例 #44
0
        /// <summary>
        /// 获取Post请求正文内容    表单
        /// </summary>
        /// <param name="requestItem"></param>
        /// <returns></returns>
        private IHttpContent GetHttpFormUrlEncodedContent(HttpItem requestItem)
        {
            IHttpContent result = null;

            KeyValuePairCollection <string, string> keyValueList = new KeyValuePairCollection <string, string>();;

            if (requestItem.PostDataCollection?.Count > 0)
            {
                keyValueList.AddRange(requestItem.PostDataCollection);
            }
            if (!string.IsNullOrWhiteSpace(requestItem.PostData))
            {
                string[] formdatas = requestItem.PostData.Split('&');
                if (formdatas != null && formdatas.Length > 0)
                {
                    foreach (var item in formdatas)
                    {
                        string[] formdata = item.Split('=');
                        if (formdata.Length == 2)
                        {
                            keyValueList.Add(formdata[0], formdata[1]);
                            //keyValueList.Add(WebUtility.UrlDecode(formdata[0]), WebUtility.UrlDecode(formdata[1]));
                        }
                    }
                }
            }

            if (keyValueList.Count > 0)
            {
                result = new HttpFormUrlEncodedContent(keyValueList);
            }

            return(result);
        }
コード例 #45
0
ファイル: Login.cs プロジェクト: yzyDavid/ZJUWLANManager
        /// <summary>
        /// 约定成功登陆返回0,不成功返回错误代码,未知返回-1
        /// </summary>
        /// <returns></returns>
        public async Task<int> DoLogin()
        {
            var httpClient = new HttpClient();
            var requestUrl = "https://net.zju.edu.cn/cgi-bin/srun_portal";
            var formcontent = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("action","login"),
                new KeyValuePair<string, string>("username",_mAccount.Username),
                new KeyValuePair<string, string>("password",_mAccount.Password),
                new KeyValuePair<string, string>("ac_id","3"),
                new KeyValuePair<string, string>("type","1"),
                new KeyValuePair<string, string>("wbaredirect",@"http://www.qsc.zju.edu.cn/"),
                new KeyValuePair<string, string>("mac","undefined"),
                new KeyValuePair<string, string>("user_ip",""),
                new KeyValuePair<string, string>("is_ldap","1"),
                new KeyValuePair<string, string>("local_auth","1"),
            });
            var response = await httpClient.PostAsync(new Uri(requestUrl), formcontent);
            if (response.Content != null)
            {
                string textMessage = await response.Content.ReadAsStringAsync();
                Debug.WriteLine(textMessage);
            }

            httpClient.Dispose();

            return -1;
        }
コード例 #46
0
 public static async void HttpPost(string id, string phone, string image, string name, string content, string time, string atName, string atPhone, string atImage)
 {
     try
     {
         HttpClient                httpClient = new HttpClient();
         string                    posturi    = Config.apiCommentPublish;
         HttpRequestMessage        request    = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
         HttpFormUrlEncodedContent postData   = new HttpFormUrlEncodedContent(
             new List <KeyValuePair <string, string> >
         {
             new KeyValuePair <string, string>("id", id),
             new KeyValuePair <string, string>("phone", phone),
             new KeyValuePair <string, string>("image", image),
             new KeyValuePair <string, string>("name", name),
             new KeyValuePair <string, string>("content", content),
             new KeyValuePair <string, string>("time", time),
             new KeyValuePair <string, string>("atName", atName),
             new KeyValuePair <string, string>("atPhone", atPhone),
             new KeyValuePair <string, string>("atImage", atImage),
         }
             );
         request.Content = postData;
         HttpResponseMessage response = await httpClient.SendRequestAsync(request);
     }
     catch (Exception ex)
     {
         HelpMethods.Msg(ex.Message.ToString());
     }
 }
コード例 #47
0
        private async void lockTapped(object sender, TappedRoutedEventArgs e)
        {
            HttpClient clientOb = new HttpClient();

            pairs.Clear();
            pairs.Add("locked", "1");
            HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);

            progress.Visibility = Visibility.Visible;
            lock1.Visibility    = Visibility.Collapsed;
            unlock1.Visibility  = Visibility.Collapsed;

            await clientOb.PostAsync(connectionUri, formContent);

            HttpResponseMessage response = await clientOb.PostAsync(connectionUri, formContent);

            if (!response.IsSuccessStatusCode)
            {
                var dialog = new MessageDialog("Error while closing your suitecase", "Error");
                await dialog.ShowAsync();
            }
            else
            {
                progress.Visibility  = Visibility.Collapsed;
                lock1.Visibility     = Visibility.Collapsed;
                unlock1.Visibility   = Visibility.Visible;
                txtStatus.Text       = "Your Suitcase is Locked";
                txtChangeStatus.Text = "(Tap to unlock it)";
            }
            clientOb.Dispose();
        }
コード例 #48
0
        public async void Add(string token, string name)
        {
            var category = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("Name", name),
            });

            this.HttpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", token);
            var response = await this.HttpClient.PostAsync(new Uri(ServerUrlConstants.baseUrl + "exercises"), category);
        }
コード例 #49
0
ファイル: HttpConnection.cs プロジェクト: milo2005/W10_Clima
        public async void requestByPostForm(string url, List<KeyValuePair<String, String>> form) {
            Uri uri = new Uri(url);
            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(form);

            HttpMediaTypeHeaderValue contentType = 
                new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.ContentType = contentType;

            HttpResponseMessage response = await client.PostAsync(uri, content);
            string rta = await response.Content.ReadAsStringAsync();
            httpRta.setRta(rta);
        }
コード例 #50
0
ファイル: slot.xaml.cs プロジェクト: rohit101293/RoadPlex
        static async Task AsyncTask(Dictionary<string, string> pairs)
        {
            Uri signup_uri = new Uri(SLOT_URL);
            HttpClient client = new HttpClient();
            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(pairs);
            HttpResponseMessage res = await client.PostAsync(signup_uri, content);
            if (res.IsSuccessStatusCode)
            {
                response = res.Content.ToString();

            }
        }
コード例 #51
0
ファイル: HttpHelper.cs プロジェクト: startewho/SLWeek
 public static async Task<string> GetTextByPost(string posturi, string poststr, IEnumerable<KeyValuePair<string, string>> body)
 {
     var httpClient = new HttpClient();
     //CreateHttpClient(ref httpClient);
     var postData = new HttpFormUrlEncodedContent(body);
     string responseString;
     using (var response = await httpClient.PostAsync(new Uri(posturi), postData))
     {
         responseString = await response.Content.ReadAsStringAsync();
     }
     return responseString;
 }
コード例 #52
0
ファイル: ManageAccount.xaml.cs プロジェクト: kleitz/WPApp
        public async void updatePassword(string newPassword)
        {
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("value", newPassword);

            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);
            var result = await RequestToServer.sendPutRequest("user/password", content);

            JObject jsonObject = JObject.Parse(result);
            MessageBox.Show(jsonObject.Value<string>("message"));
        }
コード例 #53
0
ファイル: UsersService.cs プロジェクト: Producenta/MyFitness
        public async Task<HttpStatusCode> RegisterUser(string userName, string email, string password, string confirmPassword)
        {
            var user = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("Email", email),
                new KeyValuePair<string, string>("UserName", userName),
                new KeyValuePair<string, string>("Password", password),
                new KeyValuePair<string, string>("ConfirmPassword", confirmPassword)
            });

            var response = await this.HttpClient.PostAsync(new Uri(ServerUrlConstants.baseUrl + "Account/Register"), user);
            return response.StatusCode;
        }
コード例 #54
0
 //send message to another user 
 private async void btnSend_Click(object sender, RoutedEventArgs e)
 {
     HttpClient client = new HttpClient();
     Dictionary<String, String> formDataDictionary = new Dictionary<String, String>();
     formDataDictionary.Add("SenderUserName", txtSenderUserName.Text);
     formDataDictionary.Add("SenderPhoneNumber", txtSenderPhoneNumber.Text);
     formDataDictionary.Add("ReceiverUserName", txtReceiverUserName.Text);
     formDataDictionary.Add("ReceiverPhoneNumber", txtReceiverPhoneNumber.Text);
     formDataDictionary.Add("MessageData", txtMessageData.Text);
     HttpFormUrlEncodedContent formData = new HttpFormUrlEncodedContent(formDataDictionary);
     var response = await client.PostAsync(new Uri("http://localhost:43492/message/send"), formData);
     Windows.UI.Popups.MessageDialog msg = new Windows.UI.Popups.MessageDialog(await response.Content.ReadAsStringAsync() , "Response Message" );
     msg.ShowAsync();
 }
コード例 #55
0
ファイル: ApiClient.cs プロジェクト: DiabHelp/DiabHelp-App-WP
        public async Task doLoginPost(string username, string password, Action<LoginResponseBody> callback)
        {
            Uri requestUri = new Uri(baseUrl + "rest-login");
            Debug.WriteLine("login with = " + username + ":" + password);

            var keyValues = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("username", username),
                new KeyValuePair<string, string>("password", password)
            };
            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(keyValues);
            HttpResponseMessage response = await client.PostAsync(requestUri, content);
            LoginResponseBody loginResponse = JsonConvert.DeserializeObject<LoginResponseBody>(response.Content.ToString());
            callback(loginResponse);
        }
コード例 #56
0
ファイル: ManageAccount.xaml.cs プロジェクト: kleitz/WPApp
        public async void updateUserInfomation()
        {
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("fullname", "");
            postData.Add("phone", "");
            postData.Add("personalID", "");
            postData.Add("personalID_img", "");
            postData.Add("link_avatar", "");
            postData.Add("locked", "");
            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);
            var result = await RequestToServer.sendPutRequest("user", content);

            JObject jsonObject = JObject.Parse(result);
            MessageBox.Show(jsonObject.Value<string>("message"));
        }
コード例 #57
0
        public async Task<FitnessProgramViewModel> Add(string token, string name, string description, string suitableFor, string categoryName)
        {
            var fitnessProgram = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("Name", name),
                new KeyValuePair<string, string>("Description", description),
                new KeyValuePair<string, string>("SuitableFor", suitableFor),
                new KeyValuePair<string, string>("CategoryName", categoryName)
            });

            this.HttpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", token);
            var response = await this.HttpClient.PostAsync(new Uri(ServerUrlConstants.baseUrl + "fitnessPrograms"), fitnessProgram);
            var content = await response.Content.ReadAsStringAsync();
            var addedProgram = JsonConvert.DeserializeObject<FitnessProgramViewModel>(content);
            return addedProgram;
        }
        public async Task<string> ExecuteAsync(WebView webView, Grid owner)
        {
            var url = string.Format("{0}?response_type=code&client_id={1}&redirect_uri={2}", OAuthSettings.AuthorizeEndpoint,
               Uri.EscapeDataString(OAuthSettings.ClientId),
               Uri.EscapeDataString("https://returnurl"));


            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();


            webView.NavigationStarting += async (s, a) =>
            {
                if (a.Uri.ToString().StartsWith("https://returnurl"))
                {
                    // detect return url
                    owner.Children.Remove(webView);
                    if (a.Uri.Query.StartsWith("?code="))
                    {
                        var code = Uri.UnescapeDataString(a.Uri.Query.Substring(6));
                        using (var client = new HttpClient())
                        {
                            var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>{
                                {"grant_type","authorization_code"},
                                {"code", code},
                                {"redirect_uri", "https://returnurl"},
                                {"client_id", OAuthSettings.ClientId},
                                {"client_secret", OAuthSettings.ClientSecret}
                            });
                            // exchange authorize code for an access token
                            var response = await client.PostAsync(new Uri(OAuthSettings.TokenEndpoint), content);
                            response.EnsureSuccessStatusCode();
                            var contentString = await response.Content.ReadAsStringAsync();
                            var accessTokenInfo = await JsonConvert.DeserializeObjectAsync<OAuthTokenInfo>(contentString);
                            OAuthSettings.AccessToken = accessTokenInfo.AccessToken;
                            OAuthSettings.RefreshToken = accessTokenInfo.RefreshToken;

                            tcs.SetResult(accessTokenInfo.AccessToken);
                        }
                    }
                }
            };
            webView.NavigateWithHttpRequestMessage(new HttpRequestMessage(HttpMethod.Get, new Uri(url)));


            return await tcs.Task;
        }
コード例 #59
0
        public async Task<String> login(String username, String password, ProgressBar progressBar, Boolean useToken = false)
        {
            HttpResponseMessage response = null;
            String responseString = null;

            _progressBar = progressBar;
            _progressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;

            if (!useToken)
            {
                password = h.sha512(password);
            }

            try
            {
                String device_id = h.getDeviceID();
                var values = new Dictionary<string, string>
            {
                { "username", username },
                { "password", password },
                { "device_id", device_id }
            };

                HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(values);

                IProgress<HttpProgress> progress = new Progress<HttpProgress>(ProgressHandler);
                response = await httpClient.PostAsync(new Uri(settings.API + "/login/"), formContent).AsTask(cts.Token, progress);
                responseString = await response.Content.ReadAsStringAsync();
                Debug.WriteLine("login | responseString: " + responseString);
            }
            catch (TaskCanceledException)
            {
                Debug.WriteLine("login | Canceled");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("login | Error: " + ex.StackTrace);
            }
            finally
            {
                Debug.WriteLine("login | Completed");
                resetProgressBar();
            }

            return responseString;
        }
コード例 #60
0
ファイル: LoginPage.xaml.cs プロジェクト: kleitz/WPApp
        private async void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            //test();
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("email", txtbEmail.Text.Trim());
            postData.Add("password", txtbPassword.Text);
            HttpFormUrlEncodedContent content =
                new HttpFormUrlEncodedContent(postData);

            var result = await RequestToServer.sendPostRequest("user/login", content);

            JObject jsonObject = JObject.Parse(result);

            if (jsonObject.Value<string>("error").Equals("False"))
            {
                //get API key
                Global.GlobalData.APIkey = jsonObject.Value<string>("apiKey").Trim();

                //Global.GlobalData.isDriver = jsonObject.Value<bool>("driver");
                Global.GlobalData.isDriver = true;
                Global.GlobalData.customer_status = jsonObject.Value<int>("customer_status");
                Global.GlobalData.driver_status = jsonObject.Value<int>("driver_staus");

                //storage for the next login
                IsolatedStorageSettings.ApplicationSettings["isLogin"] = "******";
                IsolatedStorageSettings.ApplicationSettings["APIkey"] = Global.GlobalData.APIkey;
                IsolatedStorageSettings.ApplicationSettings["isDriver"] = Global.GlobalData.isDriver;
                IsolatedStorageSettings.ApplicationSettings["customer_status"] = Global.GlobalData.customer_status;
                IsolatedStorageSettings.ApplicationSettings["driver_status"] = Global.GlobalData.driver_status;
                IsolatedStorageSettings.ApplicationSettings.Save();
                //Navigate to MainPage
                if (GlobalData.isDriver)
                {
                    NavigationService.Navigate(new Uri("/Driver/ItineraryManagement.xaml", UriKind.Relative));
                }
                else
                {
                    NavigationService.Navigate(new Uri("/Customer/MainMap.xaml", UriKind.RelativeOrAbsolute));
                }               
            }
            else
            {
                MessageBox.Show(jsonObject.Value<string>("message"));
            }
        }