当前位置: 首页>>代码示例>>C#>>正文


C# Http.FormUrlEncodedContent类代码示例

本文整理汇总了C#中System.Net.Http.FormUrlEncodedContent的典型用法代码示例。如果您正苦于以下问题:C# FormUrlEncodedContent类的具体用法?C# FormUrlEncodedContent怎么用?C# FormUrlEncodedContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


FormUrlEncodedContent类属于System.Net.Http命名空间,在下文中一共展示了FormUrlEncodedContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MashapeFacebookLogin

        public async Task MashapeFacebookLogin()
        {
            //NOTE: Check App.xaml.cs for the variables that you need to fill in

            var targeturi = "https://ismaelc-facebooktest.p.mashape.com/oauth_url";

            var client = new System.Net.Http.HttpClient();

            HttpContent content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("consumerKey", App.ConsumerKey),
                new KeyValuePair<string, string>("consumerSecret", App.ConsumerSecret),
                new KeyValuePair<string, string>("callbackUrl", App.CallbackUrl)
            });

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.Add("X-Mashape-Authorization", App.MashapeHeader);

            progressRing.IsActive = true;
            btnLogin.IsEnabled = false;
            var response = await client.PostAsync(targeturi, content);
            progressRing.IsActive = false;
            btnLogin.IsEnabled = true;

            if (response.IsSuccessStatusCode)
            {
                string respContent = await response.Content.ReadAsStringAsync();
                string loginUrl = await Task.Run(() => JsonObject.Parse(respContent).GetNamedString("url"));

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                                        WebAuthenticationOptions.None,
                                                        new Uri(loginUrl),
                                                        new Uri(App.CallbackUrl));

                
                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    btnLogin.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                    var callBackUrl = WebAuthenticationResult.ResponseData.ToString();
                    //Where's ParseQueryString when you need it...
                    App.AccessToken = GetParameter(callBackUrl, "accessToken");
                    //App.AccessSecret = GetParameter(callBackUrl, "accessSecret");

                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    throw new InvalidOperationException("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    // The user canceled the authentication
                }
            }
            else
            {
                //The POST failed, so update the UI accordingly
                //txtBlockResult.Text = "Error";
            }
        }
开发者ID:ismaelc,项目名称:MashapeFBSentimentExample,代码行数:60,代码来源:MainPage.xaml.cs

示例2: ChangeUserProfile

        public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location,
            UserAccountEntity userAccountEntity)
        {
            if (userAccountEntity.GetAccessToken().Equals("refresh"))
            {
                await Auth.RefreshAccessToken(userAccountEntity);
            }
            var param = new Dictionary<String, String>();
            if (!string.IsNullOrEmpty(name)) param.Add("name", name);
            if (!string.IsNullOrEmpty(url)) param.Add("url", url);
            if (!string.IsNullOrEmpty(location)) param.Add("location", location);
            if (!string.IsNullOrEmpty(description)) param.Add("description", description);

            var theAuthClient = new HttpClient();
            HttpContent header = new FormUrlEncodedContent(param);
            var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header};
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
            try
            {
                HttpResponseMessage response = await theAuthClient.SendAsync(request);
                return response.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:happy-ryo,项目名称:CrouMetro,代码行数:27,代码来源:UserManager.cs

示例3: SetupAutoCADIOContainer

        /// <summary>
        /// Does setup of AutoCAD IO. 
        /// This method will need to be invoked once before any other methods of this
        /// utility class can be invoked.
        /// </summary>
        /// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param>
        /// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param>
        public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret)
        {
            try
            {
                String clientId = autocadioclientid;
                String clientSecret = autocadioclientsecret;

                Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/");
                container = new AIO.Operations.Container(uri);
                container.Format.UseJson();

                using (var client = new HttpClient())
                {
                    var values = new List<KeyValuePair<string, string>>();
                    values.Add(new KeyValuePair<string, string>("client_id", clientId));
                    values.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                    values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                    var requestContent = new FormUrlEncodedContent(values);
                    var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);
                    _accessToken = resValues["token_type"] + " " + resValues["access_token"];
                    if (!string.IsNullOrEmpty(_accessToken))
                    {
                        container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message));
                container = null;
                throw;
            }
        }
开发者ID:CADblokeCADforks,项目名称:library-dotnet-autocad.io,代码行数:42,代码来源:AutoCADIOUtilities.cs

示例4: GetAuthorizationToken

        /// <summary>
        /// Makes a HTTP call to the OAuth2 endpoint for getting the OAuth2 token that can be used for
        /// further HTTP communication with Dinero.
        /// </summary>
        /// <returns></returns>
        public async Task<AuthorizationToken> GetAuthorizationToken()
        {
            var clientInfo = _client.Id + ":" + _client.Secret;
            using (var client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(_bodyContentParameters.GetBodyParameters());
                var request = new HttpRequestMessage
                {
                    RequestUri = _oAuth2TokenEndpoint,
                    Method = HttpMethod.Post,
                    Content = content
                };
                request.Headers.Add("Authorization", string.Format("Basic {0}", clientInfo.Base64Encode()));

                var result = await client.SendAsync(request).ConfigureAwait(false);
                var resultContent = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
                var definition = new { Access_Token = "", Token_Type = "", Expires_In = 0, Refresh_Token = ""};
                try
                {
                    var resultObj = JsonConvert.DeserializeAnonymousType(resultContent, definition);

                    if (resultObj.Access_Token == null)
                        throw new DineroAuthenticationException("Could not retrieve access token.");

                    return new AuthorizationToken(resultObj.Access_Token, DateTime.Now.AddSeconds(resultObj.Expires_In).AddMinutes(-5), resultObj.Refresh_Token);
                }
                catch (Exception e)
                {
                    throw new DineroAuthenticationException("Could not retrieve access token.",e);
                }
            }
        }
开发者ID:DineroRegnskab,项目名称:dinero-csharp-sdk,代码行数:37,代码来源:DineroOauth2Client.cs

示例5: Authenticate

        public async Task Authenticate()
        {
            var loginRequestData = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("username", _username),
                new KeyValuePair<string, string>("password", _password)
            });

            var response = await httpClient.PostAsync("/user/login", loginRequestData);
            response.EnsureSuccessStatusCode();

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

            dynamic jsonData = JsonConvert.DeserializeObject(responseBody);

            if (jsonData == null)
                throw new NestException(response);

            if (jsonData.urls == null)
                throw new NestException(response);

            AccessToken = jsonData.access_token;
            AccessTokenExpiration = jsonData.expires_in;
            UserId = jsonData.userid;
            var urls = jsonData.urls;
            ApiUrl = urls.rubyapi_url;
            TransportApiBaseAddress = urls.transport_url;
            WeatherUrl = urls.weather_url;
        }
开发者ID:noelhx,项目名称:NestThermostatLogger,代码行数:29,代码来源:NestClient.User.cs

示例6: ChkVerifyCodeAnsyn

 public static async Task<bool> ChkVerifyCodeAnsyn(string verifyNo)
 {
     try
     {
         var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip };
         using (var httpClient = new HttpClient(handler))
         {
             httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn");
             httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin);
             httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer);
             httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131");
             ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
             // 构造POST参数
             var data = new FormUrlEncodedContent(new Dictionary<string, string>()
             {
                {"randCode", verifyNo},
                {"rand", "sjrand"}
             });
             var response = await httpClient.PostAsync(ConstantKey.loginChkVcode, data);
             response.EnsureSuccessStatusCode();
             string content = await response.Content.ReadAsStringAsync();
             if (string.IsNullOrEmpty(content) || !content.Contains("Y") || !content.Contains("true")) return false;
             return true;
         }
     }
     catch (Exception ex)
     {
         return false;
     }
 }
开发者ID:zhouyongtao,项目名称:TicketHelper,代码行数:30,代码来源:TicketHandler.cs

示例7: CreateTag

        public string CreateTag(Tag model, UserData userData)
        {
            try
            {
                client = new HttpClient();
                var postData = new List<KeyValuePair<string, string>>();
                postData.Add(new KeyValuePair<string, string>("name", model.name));

                HttpContent content = new FormUrlEncodedContent(postData);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                content.Headers.Add("Timestamp", userData.Timestamp.ToString());
                content.Headers.Add("Digest", userData.AuthenticationHash);
                content.Headers.Add("Public-Key", userData.PublicKey);

                client.PostAsync("http://localhost:3000/tag", content)
                    .ContinueWith(postTask =>
                    {
                        postTask.Result.EnsureSuccessStatusCode();
                        var result = postTask.Result.Content.ReadAsStringAsync();
                        client.Dispose();
                        return result;

                    });

            }
            catch (Exception ex)
            {
                throw ex;

            }
            return null;
        }
开发者ID:robertzur,项目名称:ContactBookWebClient,代码行数:32,代码来源:TagEndpoint.cs

示例8: Post

        public static string Post(string url, PostBody postBody, int timeout = 5000)
        {
            try
            {
                Logger.Debug($"Post\t{url}");

                using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
                using (var client = new HttpClient(handler))
                {
                    var content = new FormUrlEncodedContent(postBody.Body);
                    var magicCodeName = string.Empty;
                    if (Config.TryGet("MagicCodeType", out magicCodeName))
                    {
                        var magicCodeValue = Config.TryGet("MagicCodeValue", "");
                        var magicCodePath = Config.TryGet("MagicCodePath", "/");
                        var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com");
                        handler.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain));
                    }
                    var result = client.PostAsync(url, content).Result;
                    result.EnsureSuccessStatusCode();

                    return result.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.ToString());
                return e.Message;
            }
        }
开发者ID:chinaboard,项目名称:WeeklyRobot,代码行数:30,代码来源:HttpHelper.cs

示例9: PostStringAsync

 public async Task<String> PostStringAsync(Uri uri, IDictionary<String, String> content) {
   using (var http = new HttpClient()) {
     var formContent = new FormUrlEncodedContent(content);
     var response = await http.PostAsync(uri, formContent);
     return await response.Content.ReadAsStringAsync();
   }
 }
开发者ID:NNastasya,项目名称:igooana,代码行数:7,代码来源:Connection.cs

示例10: CheckStatusCodeIs

        public Step CheckStatusCodeIs(HttpStatusCode codeToMatch)
        {
            var formContent = new FormUrlEncodedContent(_formContent);
            SetUpDefaultHeaders();
            Stopwatch stopWatch = Stopwatch.StartNew();
            var task = Post(formContent);
            string htmlContent = task.Result.Content.ReadAsStringAsync().Result;
            stopWatch.Stop();
            Console.WriteLine("Took {0} Milliseconds", stopWatch.ElapsedMilliseconds);
            if (!string.IsNullOrEmpty(htmlContent))
            {
                if (htmlContent.Contains("__EVENTVALIDATION"))
                {
                    CurrentEventValidation = HttpScraper.GetEventValidationFromHtml(htmlContent);
                }
                if (htmlContent.Contains("__VIEWSTATE"))
                {
                    CurrentViewState = HttpScraper.GetViewStateFromHtml(htmlContent);
                }
            }

            if (task.Result != null)
            {
                task.Result.StatusCode.Should().Be(codeToMatch);
            }
            else
            {
                throw new Exception("Http Status code is null");
            }
            Step.CurrentEventValidation = CurrentEventValidation;
            Step.CurrentViewState = CurrentViewState;
            Step.CurrentHtml = htmlContent;
            Dispose();
            return Step;
        }
开发者ID:TomPallister,项目名称:PerformanceDsl,代码行数:35,代码来源:PostRequest.cs

示例11: GetAuthorizationCode

        private async Task<SuccessfulAuthenticationResponse> GetAuthorizationCode(AuthorizationGrantRequest request)
        {
            var url = request.Uri;

            var data = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("scope", "openid"),
                new KeyValuePair<string, string>("response_type", "code"),
                new KeyValuePair<string, string>("client_id", request.ClientId),
                new KeyValuePair<string, string>("client_secret", request.ClientSecret),
                new KeyValuePair<string, string>("prompt", "none"),
                new KeyValuePair<string, string>("redirect_uri", request.RedirectUri),
                new KeyValuePair<string, string>("username", request.Username),
                new KeyValuePair<string, string>("password", request.Password),
            });

            var client = new HttpClient();
            var response = await client.PostAsync(url, data);
            var content = await response.Content.ReadAsStringAsync();

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                var error = JsonConvert
                    .DeserializeObject<AuthenticationErrorResponse>
                    (content);

                throw new Exception(error.error + ": " + error.error_description);
            }
            else
            {
                return JsonConvert
                   .DeserializeObject<SuccessfulAuthenticationResponse>
                   (content);
            }
        }
开发者ID:yanjustino,项目名称:CarcarahOAuth2,代码行数:35,代码来源:OAuth2Client.cs

示例12: Execute

        public async Task<JObject> Execute()
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
                throw new Exception("Network is not available.");

            var uri = GetFullUri();
#if DEBUG
            Debug.WriteLine("Invoking " + uri);
#endif

            JObject response = null;

            var httpClient = new HttpClient();
            if (_method == "GET")
            {
                HttpResponseMessage responseMessage = await httpClient.GetAsync(uri);
                var content = await responseMessage.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(content))
                    response = JObject.Parse(content);
            }
            else
            {
                var postContent = new FormUrlEncodedContent(_parameters);
                postContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                HttpResponseMessage responseMessage = await httpClient.PostAsync(uri, postContent);
                var content = await responseMessage.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(content))
                    response = JObject.Parse(content);
            }

            return response;
        }
开发者ID:justdude,项目名称:meridian,代码行数:32,代码来源:VkRequest.cs

示例13: SendCommentReply

        public static async Task<bool> SendCommentReply(string userId,string comment)
        {
            try
            {
                var client = await MalHttpContextProvider.GetHttpContextAsync();

                var contentPairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("profileMemId", userId),
                new KeyValuePair<string, string>("commentText", comment),
                new KeyValuePair<string, string>("area", "2"),
                new KeyValuePair<string, string>("csrf_token", client.Token),
                new KeyValuePair<string, string>("commentSubmit", "1")
            };
                var content = new FormUrlEncodedContent(contentPairs);

                var response =
                    await client.PostAsync("/addcomment.php", content);

                //edit comment function - not sure what it does
                // /includes/ajax.inc.php?t=73
                //com id - token
                //id = 31985758 & csrf_token = dfsdfsd
                //client.PostAsync("/includes/ajax.inc.php?t=73")

                return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.SeeOther;
            }
            catch (WebException)
            {
                MalHttpContextProvider.ErrorMessage("Messages");
                return false;
            }
        }
开发者ID:Mordonus,项目名称:MALClient,代码行数:33,代码来源:ProfileCommentQueries.cs

示例14: PlayGame

        private static async void PlayGame(string[] splittedInput)
        {
            var gameId = splittedInput[1];
            var x = splittedInput[2];
            var y = splittedInput[3];
            var httpClient = new HttpClient();

            using (httpClient)
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("GameId", gameId), 
                    new KeyValuePair<string, string>("PositionX", x), 
                    new KeyValuePair<string, string>("PositionY", y), 
                });
                var response = await httpClient.PostAsync("http://localhost:62859/api/Games/play", content);

                if (!response.IsSuccessStatusCode)
                {
                    var messageObj = response.Content.ReadAsAsync<ErrorDTO>().Result;
                    Console.WriteLine(messageObj.Message + "; Description: " + messageObj.ExceptionMessage);
                }
                else
                {
                    var gameid = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine("Game is running, id: " + gameid);
                }
            }
        }
开发者ID:StefanBratovanov,项目名称:WebSevicesAndCloud,代码行数:30,代码来源:ConsoleClientMain.cs

示例15: SendComment

        public static async Task<bool> SendComment(string username,string userId,string comment)
        {
            try
            {
                var client = await MalHttpContextProvider.GetHttpContextAsync();

                var contentPairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("profileMemId", userId),
                new KeyValuePair<string, string>("commentText", comment),
                new KeyValuePair<string, string>("profileUsername", username),
                new KeyValuePair<string, string>("csrf_token", client.Token),
                new KeyValuePair<string, string>("commentSubmit", "Submit Comment")
            };
                var content = new FormUrlEncodedContent(contentPairs);

                var response =
                    await client.PostAsync("/addcomment.php", content);

                return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.SeeOther;
            }
            catch (WebException)
            {
                MalHttpContextProvider.ErrorMessage("Messages");
                return false;
            }
        }
开发者ID:Mordonus,项目名称:MALClient,代码行数:27,代码来源:ProfileCommentQueries.cs


注:本文中的System.Net.Http.FormUrlEncodedContent类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。