.Net整合Json实现REST服务客户端的方法详解
前言
本文主要给大家介绍了关于.Net整合Json实现REST服务客户端的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一.准备工作
1.点击官网 或本地下载支持.Net4.0的Json插件Newtonsoft.Json
2.找到%压缩包%\Bin\net40\Newtonsoft.Json.dll,在工程中引用
二.相关代码介绍
1.HttpClientUtil.cs封装REST方法
usingNewtonsoft.Json; usingSystem; usingSystem.Collections.Generic; usingSystem.IO; usingSystem.Linq; usingSystem.Net; usingSystem.Text; namespacepsi.Common { publicclassHttpClientUtil { //REST@GET方法,根据泛型自动转换成实体,支持ListpublicstaticTdoGetMethodToObj (stringurl) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url); request.Method="get"; request.ContentType="application/json;charset=UTF-8"; HttpWebResponseresponse=null; try { response=(HttpWebResponse)request.GetResponse(); } catch(WebExceptione) { response=(HttpWebResponse)e.Response; returndefault(T); } stringjson=getResponseString(response); returnJsonConvert.DeserializeObject (json); } //将HttpWebResponse返回结果转换成string privatestaticstringgetResponseString(HttpWebResponseresponse) { stringjson=null; using(StreamReaderreader=newStreamReader(response.GetResponseStream(),System.Text.Encoding.GetEncoding("UTF-8"))) { json=reader.ReadToEnd(); } returnjson; } //获取异常信息 privatestaticstringgetRestErrorMessage(HttpWebResponseerrorResponse) { stringerrorhtml=getResponseString(errorResponse); stringerrorkey="UnhandledException:"; errorhtml=errorhtml.Substring(errorhtml.IndexOf(errorkey)+errorkey.Length); errorhtml=errorhtml.Substring(0,errorhtml.IndexOf("\n")); returnerrorhtml; } //REST@POST方法 publicstaticTdoPostMethodToObj (stringurl,stringjsonBody) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url); request.Method="post"; request.ContentType="application/json;charset=UTF-8"; varstream=request.GetRequestStream(); using(varwriter=newStreamWriter(stream)) { writer.Write(jsonBody); writer.Flush(); } HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); stringjson=getResponseString(response); returnJsonConvert.DeserializeObject (json); } //REST@PUT方法 publicstaticstringdoPutMethod(stringurl) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url); request.Method="put"; request.ContentType="application/json;charset=UTF-8"; HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); using(StreamReaderreader=newStreamReader(response.GetResponseStream(),System.Text.Encoding.GetEncoding("UTF-8"))) { returnreader.ReadToEnd(); } } //REST@PUT方法,带发送内容主体 publicstaticTdoPutMethodToObj (stringurl,stringjsonBody) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url); request.Method="put"; request.ContentType="application/json;charset=UTF-8"; request.Timeout=30*1000; varstream=request.GetRequestStream(); using(varwriter=newStreamWriter(stream)) { writer.Write(jsonBody); writer.Flush(); } HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); stringjson=getResponseString(response); returnJsonConvert.DeserializeObject (json); } //REST@DELETE方法 publicstaticbooldoDeleteMethod(stringurl) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url); request.Method="delete"; request.ContentType="application/json;charset=UTF-8"; HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); using(StreamReaderreader=newStreamReader(response.GetResponseStream(),System.Text.Encoding.GetEncoding("UTF-8"))) { stringresponseString=reader.ReadToEnd(); if(responseString.Equals("1")) { returntrue; } returnfalse; } } } }
2.调用REST服务端方法,以Json作为数据格式
//////取得升级服务端的url地址 /// ///privateStringgetServerUrl() { Stringresult=""; UpgraderClientupgraderClient=getUpgraderClient(); if(upgraderClient!=null) { result+="http://"+upgraderClient.serverIP+ ":"+upgraderClient.serverPort+ "/upgraderServer/service/upgrade.do"; } returnresult; } /// ///测试与升级服务端的连接 /// ///publicbooltestConnect() { FileRequestfileReq=newFileRequest(); fileReq.type=(int)RequestType.TEST_CONNECT; stringjsonData=JsonConvert.SerializeObject(fileReq); FileResponserep=null; try { rep=HttpClientUtil.doPostMethodToObj (getServerUrl(),jsonData); }catch { thrownewException("连接远程服务端失败!"); } returnrep.status==200; }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。