前言
本文主要给大家介绍了关于.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; }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。