首先说一下HttpRequest、WebClient和HttpClient的关系:HttpRequest是基层的请求方式,WebClient是对HttpRequest的简化封装,在WebClient中有对HttpRequest的默认设置;HttpClient是重写的请求方式,相对于HttpRequest更简单实现异步请求,是.NetCore中更推崇的方式。
说明:以下代码中 在GetAccessToken(Async)中调用了调用了PostMail(Async)方式,其中在GetAccessToken(Async)实现GET请求,在PostMail(Async)中实现POST请求
一、对比一下HttpRequest与HttpClient实现GET请求的过程区别(其实很相似,但HttpClient轻松实现了异步)
1)HttpRequest的GET请求
public ActionResult<string> GetAccessToken() { //GET获取accessToken的参数 corid string uri = "你的URL"; //创建请求 //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); //WebClient是对HttpWebRequest的抽象,WebClient使用简单,但速度慢;Restsharp兼具WebClient和HttpWebClient的优点;HttpClient是.NetCore中的概念,更适合异步编程 WebRequest request = WebRequest.Create(uri); //请求设置 request.Credentials = CredentialCache.DefaultCredentials; //创建应答接收 WebResponse response = request.GetResponse(); //创建应答读写流 string accessToken; using (Stream streamResponse=response.GetResponseStream()) { StreamReader reader = new StreamReader(streamResponse); string responseFromServer = reader.ReadToEnd(); JObject res = (JObject)JsonConvert.DeserializeObject(responseFromServer); accessToken = res["access_token"].ToString(); reader.Close(); } //获得许可证凭证 PostMail(accessToken); //关闭响应 response.Close(); return