• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Http.FormUrlEncodedContent类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Validate

        public RecaptchaResponse Validate(RecaptchaRequest recaptchaRequest)
        {
            var result = new RecaptchaResponse
            {
                Success = false
            };

            var request = new FormUrlEncodedContent(new[]
                 {
                    new KeyValuePair<string, string>("secret", _configurationManager.GetAppSettingAs<string>(AppSettingsRecaptchaSecretKey)),
                    new KeyValuePair<string, string>("response", recaptchaRequest.Token),
                    new KeyValuePair<string, string>("remoteip", recaptchaRequest.IpAddress)
                });

            var response = _client.PostAsync(ApiUrl, request).Result;
            if (response.IsSuccessStatusCode)
            {
                var contents = response.Content.ReadAsStringAsync().Result;
                if (!string.IsNullOrEmpty(contents))
                {
                    result = JsonConvert.DeserializeObject<RecaptchaResponse>(contents, new StringEnumConverter());
                }
            }

            return result;
        }
开发者ID:hartmanns,项目名称:hartmanns-io,代码行数:26,代码来源:ValidateRecaptcha.cs


示例17: InsertFile

        public bool InsertFile(FileStruct file)
        {

            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(RequestUri.BaseUrl);
                    var content = new FormUrlEncodedContent(new[]
                    {
                    new KeyValuePair<string, string>("vkFileId", file.vkFileId.ToString()),
                    new KeyValuePair<string, string>("filename", file.filename),
                    new KeyValuePair<string, string>("dialog", file.dialogId),
                    new KeyValuePair<string, string>("tags", string.Join(",",file.tags))
                });
                    var result = client.PostAsync(RequestUri.InsertFileRequestUri, content).Result;
                    string resultContent = result.Content.ReadAsStringAsync().Result;
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
开发者ID:orinichevd,项目名称:BVk,代码行数:25,代码来源:Program.cs


示例18: GetAuthToken

        async Task<string> GetAuthToken(bool forceFetch = false)
        {
            if (!forceFetch && lastTokenFetch > DateTime.Now - TimeSpan.FromHours(48))
            {
                return token;
            }

            var pairs = new Dictionary<string, string> {
				{ "username", username },
				{ "password", password }
			};

            var content = new FormUrlEncodedContent(pairs);

            var response = await client.PostAsync(AuthUrl, content);
            var responseContent = await response.Content.ReadAsStringAsync();
            var jsonResponse = JObject.Parse(responseContent);
            if (jsonResponse["error"] != null)
            {
                throw new ApplicationException((string)jsonResponse["error"]);
            }
            token = (string)jsonResponse["token"];
            lastTokenFetch = DateTime.Now;
            return token;
        }
开发者ID:sdesbure,项目名称:Jackett,代码行数:25,代码来源:T411.cs


示例19: UpdateStatus

        public static async Task<bool> UpdateStatus(String status, long? inReply, bool? inQuote, bool? trim,
            UserAccountEntity userAccountEntity)
        {
            var param = new Dictionary<String, String> {{"status", status}};
            if (inReply != null) param.Add("in_reply_to_status_id", inReply.ToString());
            if (inQuote == true) param.Add("in_reply_with_quote", true.ToString());
            if (trim == true) param.Add("trim_user", true.ToString());

            var theAuthClient = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.STATUS_UPDATE);

            string accessToken = userAccountEntity.GetAccessToken();
            if (accessToken.Equals("refresh"))
            {
                await Auth.RefreshAccessToken(userAccountEntity);
                accessToken = userAccountEntity.GetAccessToken();
            }

            HttpContent header = new FormUrlEncodedContent(param);
            request.Content = header;
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            try
            {
                HttpResponseMessage response = await theAuthClient.SendAsync(request);
                return response.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:happy-ryo,项目名称:CrouMetro,代码行数:31,代码来源:StatusManager.cs


示例20: GetTokenFromGrant

        public override async Task<string> GetTokenFromGrant(string grant)
        {
            string token = "";

            using (var client = new HttpClient())
            {
                Dictionary<string, string> postvalues = new Dictionary<string, string>
                {
                   { "code", grant },
                   { "client_id", AppID },
                   { "client_secret", AppSecret },
                   { "redirect_uri", RedirectURI },
                   { "grant_type", "authorization_code" }
                };

                var content = new FormUrlEncodedContent(postvalues);

                var response = await client.PostAsync("https://www.googleapis.com/oauth2/v4/token", content);

                var responseString = await response.Content.ReadAsStringAsync();
                Dictionary<string, string> responseJSON = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString);
                token = responseJSON["access_token"];
            }

            return token;
        }
开发者ID:eziante,项目名称:GenericLoginFramework,代码行数:26,代码来源:GoogleProvider.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Http.HttpClient类代码示例发布时间:2022-05-26
下一篇:
C# Http.DelegatingHandler类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap