HttpClient _httpClient = new HttpClient(); var clientId = Config.GetValue("AuthUser"); var clientSecret = Config.GetValue("AuthPass"); var apiHost = Config.GetValue("ApiHost"); _httpClient.BaseAddress = new Uri(apiHost); var parameters = new Dictionary<string, string>(); parameters.Add("grant_type", "password"); parameters.Add("username", account); parameters.Add("password", password); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret)) ); var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters)); var responseValue = await response.Content.ReadAsStringAsync(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var access_token = JObject.Parse(responseValue)["access_token"].Value<string>(); return new TokenResult() { Message = "ok", access_token = access_token }; //return JObject.Parse(responseValue)["access_token"].Value<string>(); } else { var modelstate = JObject.Parse(responseValue)["ModelState"][0].Value<string>(); return new TokenResult() { Message = modelstate }; } //string url = Config.GetValue("ApiHost") + "/token"; ////设置HttpClientHandler的AutomaticDecompression //var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; ////创建HttpClient(注意传入HttpClientHandler) //using (var http = new HttpClient(handler)) //{ // //使用FormUrlEncodedContent做HttpContent // var content = new FormUrlEncodedContent(new Dictionary<string, string>() // { // {"grant_type", "password"},//键名必须为空 // { "username", account}, // {"password", password }, // }); // //await异步等待回应 // var response = await http.PostAsync(url, content); // //确保HTTP成功状态值 // response.EnsureSuccessStatusCode(); // //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) // var responseValue = await response.Content.ReadAsStringAsync(); // if (response.StatusCode == System.Net.HttpStatusCode.OK) // { // return JObject.Parse(responseValue)["access_token"].Value<string>(); // } // else // { // return string.Empty; // } //}
学习交流群:364976091