HttpClient替换HttpWebRequest--以GET和POST请求为例说明
程序员文章站
2022-03-20 07:59:35
首先说一下HttpRequest、WebClient和HttpClient的关系:HttpRequest是基层的请求方式,WebClient是对HttpRequest的简化封装,在WebClient中有对HttpRequest的默认设置;HttpClient是重写的请求方式,相对于HttpReque ......
首先说一下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 "success"; }
2)httpclient的get请求
public async task<actionresult<string>> getaccesstokenasync() { string uri = "你的url"; httpclienthandler handler = new httpclienthandler { //设置是否发送凭证信息,有的服务器需要验证身份,不是所有服务器需要 usedefaultcredentials = false }; httpclient httpclient = new httpclient(handler); httpresponsemessage response = await httpclient.getasync(uri); response.ensuresuccessstatuscode(); string accesstoken; //回复结果直接读成字符串 string resp = await response.content.readasstringasync(); jobject json = (jobject)jsonconvert.deserializeobject(resp); accesstoken = json["access_token"].tostring(); //采用流读数据 //using (stream streamresponse = await response.content.readasstreamasync()) //{ // streamreader reader = new streamreader(streamresponse); // string responsefromserver = reader.readtoend(); // jobject res = (jobject)jsonconvert.deserializeobject(responsefromserver); // accesstoken = res["access_token"].tostring(); // reader.close(); //} //获得许可证凭证 postmailasync(accesstoken); //关闭响应 return "success"; }
二、对比一下httprequest与httpclient实现post请求的过程区别
1)httprequest的post请求
public void postmail(string accesstoken) { //post的api string uri = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accesstoken; //创建请求 webrequest mywebrequest = webrequest.create(uri); //请求设置 mywebrequest.credentials = credentialcache.defaultcredentials; mywebrequest.contenttype = "application/json;charset=utf-8"; mywebrequest.method = "post"; //向服务器发送的内容 using (stream streamresponse = mywebrequest.getrequeststream()) { //创建json格式的发送内容 jobject postedjobject = new jobject { //在此处设置发送内容及对象 { "touser", "heavy" }, { "msgtype", "text" }, { "agentid", 1000002 } }; jobject text = new jobject { {"content","内容来自网站--内容可自行编辑--heavy"} }; postedjobject.add("text", text); postedjobject.add("safe", 0); //将传送内容编码 string paramstring = postedjobject.tostring(newtonsoft.json.formatting.none, null); byte[] bytearray = encoding.utf8.getbytes(paramstring); //向请求中写入内容 streamresponse.write(bytearray, 0, bytearray.length); } //创建应答 webresponse mywebresponse = mywebrequest.getresponse(); //创建应答的读写流 string responsefromserver; using (stream streamresponse = mywebresponse.getresponsestream()) { streamreader streamread = new streamreader(streamresponse); responsefromserver = streamread.readtoend(); } //关闭应答 mywebresponse.close(); }
2)httpclient的post请求
public async void postmailasync(string accesstoken) { string uri = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accesstoken; httpclienthandler handler = new httpclienthandler { usedefaultcredentials = true, }; httpclient httpclient = new httpclient(handler); jobject postedjobject = new jobject { //在此处设置发送内容及对象 { "touser", "heavy" }, { "msgtype", "text" }, { "agentid", 1000002 } }; jobject text = new jobject { {"content","内容来自网站--内容可自行编辑--heavy"} }; postedjobject.add("text", text); postedjobject.add("safe", 0); //将传送内容编码 string paramstring = postedjobject.tostring(newtonsoft.json.formatting.none, null); //byte[] bytearray = encoding.utf8.getbytes(paramstring); httpcontent httpcontent = new stringcontent(paramstring,encoding.utf8,"application/json"); httpresponsemessage response = await httpclient.postasync(uri, httpcontent);
//用来判断是否接收成功,否则抛出异常 response.ensuresuccessstatuscode(); }
上一篇: Java面试必问通信框架NIO,原理详解