IHttpClientFactory _httpClientFactory; public HttpController(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } [HttpGet] public async Task<IActionResult> Get3() { var client = _httpClientFactory.CreateClient(); var dic = new Dictionary<string, object> { { "scope", "api1" }, { "grant_type", "password" }, { "client_id","ro.client" }, { "client_secret","secret" }, { "username","alice"}, { "password","password" } }; var dic_str = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n); HttpContent httpcontent = new StringContent(dic_str); httpcontent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var oauth_rep = await client.PostAsync("http://localhost:100/connect/token", httpcontent); var oauth_str = await oauth_rep.Content.ReadAsStringAsync(); var oauth_job = JsonConvert.DeserializeObject<JObject>(oauth_str); client.SetBearerToken(oauth_job["access_token"].ToString()); var data_rep = await client.GetStringAsync("http://localhost:101/api/values/get"); var data_job = JsonConvert.DeserializeObject<JObject>(data_rep); return Ok(data_job); }
第一部分获取token,第二部分获取数据