C#中httpclient的使用
1.使用HttpClient调用Oauth的授权接口获取access_token
1)OAuth使用的密码式
2)获取到access_token后才进行下一步
2.带着access_token调用接口
1)hearder上添加bearer方式的access_token
2)调用接口确保成功获取到返回的结果
1 try 2 { 3 string host = ConfigurationManager.AppSettings["api_host"]; 4 string username = ConfigurationManager.AppSettings["api_username"]; 5 string password = ConfigurationManager.AppSettings["api_password"]; 6 7 HttpClient httpClient = new HttpClient(); 8 9 // 设置请求头信息 10 httpClient.DefaultRequestHeaders.Add("Host", host); 11 httpClient.DefaultRequestHeaders.Add("Method", "Post"); 12 httpClient.DefaultRequestHeaders.Add("KeepAlive", "false"); // HTTP KeepAlive设为false,防止HTTP连接保持 13 httpClient.DefaultRequestHeaders.Add("UserAgent", 14 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); 15 16 //获取token 17 var tokenResponse = httpClient.PostAsync("http://" + host + "/token", new FormUrlEncodedContent(new Dictionary<string, string> { 18 {"grant_type","password"}, 19 {"username", username}, 20 {"password", password} 21 })); 22 tokenResponse.Wait(); 23 tokenResponse.Result.EnsureSuccessStatusCode(); 24 var tokenRes = tokenResponse.Result.Content.ReadAsStringAsync(); 25 tokenRes.Wait(); 26 var token = Newtonsoft.Json.Linq.JObject.Parse(tokenRes.Result); 27 var access_token = token["access_token"].ToString(); 28 29 // 调用接口发起POST请求 30 var authenticationHeaderValue = new AuthenticationHeaderValue("bearer", access_token); 31 httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue; 32 var content = new StringContent(parameter); 33 content.Headers.ContentType=new MediaTypeHeaderValue("application/json"); 34 var response = httpClient.PostAsync("http://" + host + "/" + api_address,content ); 35 36 response.Wait(); 37 response.Result.EnsureSuccessStatusCode(); 38 var res = response.Result.Content.ReadAsStringAsync(); 39 res.Wait(); 40 return Newtonsoft.Json.JsonConvert.DeserializeObject<ResultEx>(res.Result); 41 } 42 catch (Exception ex) 43 { 44 45 return ResultEx.Init(ex.Message); 46 }