您好,登錄后才能下訂單哦!
小編給大家分享一下.Net整合Json如何實(shí)現(xiàn)REST服務(wù)客戶端,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
一. 準(zhǔn)備工作
1. 點(diǎn)擊官網(wǎng) 或 本地 下載支持.Net4.0 的Json插件 Newtonsoft.Json
2. 找到 %壓縮包%\Bin\net40\Newtonsoft.Json.dll ,在工程中引用
二. 相關(guān)代碼介紹
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 方法,根據(jù)泛型自動轉(zhuǎn)換成實(shí)體,支持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 返回結(jié)果轉(zhuǎn)換成 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 方法,帶發(fā)送內(nèi)容主體 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. 調(diào)用REST服務(wù)端方法,以Json作為數(shù)據(jù)格式
/// <summary> /// 取得升級服務(wù)端的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> /// 測試與升級服務(wù)端的連接 /// </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("連接遠(yuǎn)程服務(wù)端失?。?quot;); } return rep.status == 200; }
看完了這篇文章,相信你對“.Net整合Json如何實(shí)現(xiàn)REST服務(wù)客戶端”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。