小编给大家分享一下.Net整合Json如何实现REST服务客户端,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
一. 准备工作
1. 点击官网 或 本地 下载支持.Net4.0 的Json插件 Newtonsoft.Json
2. 找到 %压缩包%\Bin\net40\Newtonsoft.Json.dll ,在工程中引用
二. 相关代码介绍
1. HttpClientUtil.cs 封装REST方法
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace psi.Common { public class HttpClientUtil { // REST @GET 方法,根据泛型自动转换成实体,支持List<T> public static T doGetMethodToObj<T>(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "get"; request.ContentType = "application/json;charset=UTF-8"; HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { response = (HttpWebResponse)e.Response; return default(T); } string json = getResponseString(response); return JsonConvert.DeserializeObject<T>(json); } // 将 HttpWebResponse 返回结果转换成 string private static string getResponseString(HttpWebResponse response) { string json = null; using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"))) { json = reader.ReadToEnd(); } return json; } // 获取异常信息 private static string getRestErrorMessage(HttpWebResponse errorResponse) { string errorhtml = getResponseString(errorResponse); string errorkey = "UnhandledException:"; errorhtml = errorhtml.Substring(errorhtml.IndexOf(errorkey) + errorkey.Length); errorhtml = errorhtml.Substring(0, errorhtml.IndexOf("\n")); return errorhtml; } // REST @POST 方法 public static T doPostMethodToObj<T>(string url, string jsonBody) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "post"; request.ContentType = "application/json;charset=UTF-8"; var stream = request.GetRequestStream(); using (var writer = new StreamWriter(stream)) { writer.Write(jsonBody); writer.Flush(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string json = getResponseString(response); return JsonConvert.DeserializeObject<T>(json); } // REST @PUT 方法 public static string doPutMethod(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "put"; request.ContentType = "application/json;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"))) { return reader.ReadToEnd(); } } // REST @PUT 方法,带发送内容主体 public static T doPutMethodToObj<T>(string url, string jsonBody) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "put"; request.ContentType = "application/json;charset=UTF-8"; request.Timeout = 30 * 1000; var stream = request.GetRequestStream(); using (var writer = new StreamWriter(stream)) { writer.Write(jsonBody); writer.Flush(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string json = getResponseString(response); return JsonConvert.DeserializeObject<T>(json); } // REST @DELETE 方法 public static bool doDeleteMethod(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "delete"; request.ContentType = "application/json;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"))) { string responseString = reader.ReadToEnd(); if (responseString.Equals("1")) { return true; } return false; } } } }
2. 调用REST服务端方法,以Json作为数据格式
/// <summary> /// 取得升级服务端的url地址 /// </summary> /// <returns></returns> private String getServerUrl() { String result = ""; UpgraderClient upgraderClient = getUpgraderClient(); if (upgraderClient != null) { result += "http://" + upgraderClient.serverIP + ":" + upgraderClient.serverPort + "/upgraderServer/service/upgrade.do"; } return result; } /// <summary> /// 测试与升级服务端的连接 /// </summary> /// <returns></returns> public bool testConnect() { FileRequest fileReq = new FileRequest(); fileReq.type = (int)RequestType.TEST_CONNECT; string jsonData = JsonConvert.SerializeObject(fileReq); FileResponse rep = null; try { rep = HttpClientUtil.doPostMethodToObj<FileResponse>(getServerUrl(), jsonData); } catch { throw new Exception("连接远程服务端失败!"); } return rep.status == 200; }
看完了这篇文章,相信你对“.Net整合Json如何实现REST服务客户端”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。