標籤:json反序列 json json序列化 json序列化對象 api
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Net.Security;using System.Security.Cryptography.X509Certificates;using System.Text;using System.Threading.Tasks;using System.Web;namespace AirMedia.Wap.Core{ public static class HttpWebHelper { /// <SUMMARY> /// httpwebrequest類中的一些屬性的集合 /// </SUMMARY> public class RequestParam { /// <SUMMARY> /// 擷取或設定request類中的Accept屬性 /// 用以設定接受的檔案類型 /// </SUMMARY> public string Accept { get; set; } /// <SUMMARY> /// 擷取或設定request類中的ContentType屬性 /// 用以佈建要求的媒體類型 /// </SUMMARY> public string ContentType { get; set; } /// <SUMMARY> /// 擷取或設定request類中的UserAgent屬性 /// 用以佈建要求的用戶端資訊 /// </SUMMARY> public string UserAgent { get; set; } /// <SUMMARY> /// 擷取或設定request類中的Method屬性 /// 可以將 Method 屬性設定為任何 HTTP 1.1 協議謂詞:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。 /// 如果 ContentLength 屬性被設定為 -1 以外的任何值,則必須將 Method 屬性設定為上傳資料的協議屬性。 /// </SUMMARY> public string Method { get; set; } /// <summary> /// 發送的資料 /// </summary> public byte[] PostData { get; set; } } /// <SUMMARY> /// 構建一個httt請求以擷取目標連結的cookies,需要傳入目標的登入地址和相關的post資訊,返回完成登入的cookies,以及返回的html內容 /// </SUMMARY> /// <PARAM name="url">登入頁面的地址</PARAM> /// <PARAM name="post">post資訊</PARAM> /// <PARAM name="strHtml">輸出的html代碼</PARAM> /// <PARAM name="rppt">請求的標題所需要的相關屬性設定</PARAM> /// <RETURNS>請求完成後的cookies</RETURNS> public static CookieCollection GetCookie(string url, RequestParam rppt, out string strHtml) { CookieCollection ckclReturn = new CookieCollection(); CookieContainer cc = new CookieContainer(); HttpWebRequest hwRequest; HttpWebResponse hwResponse; Stream stream; hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); hwRequest.CookieContainer = cc; if (rppt != null) { hwRequest.Accept = rppt.Accept; hwRequest.ContentType = rppt.ContentType; hwRequest.UserAgent = rppt.UserAgent; hwRequest.Method = rppt.Method; hwRequest.ContentLength = rppt.PostData.Length; //寫入標題 stream = hwRequest.GetRequestStream(); stream.Write(rppt.PostData, 0, rppt.PostData.Length); stream.Close(); } //發送請求擷取響應內容 try { hwResponse = (HttpWebResponse)hwRequest.GetResponse(); } catch { strHtml = ""; return ckclReturn; } stream = hwResponse.GetResponseStream(); StreamReader sReader = new StreamReader(stream, Encoding.UTF8); strHtml = sReader.ReadToEnd(); sReader.Close(); stream.Close(); //擷取緩衝內容 ckclReturn = hwResponse.Cookies; return ckclReturn; } /// <SUMMARY> /// 根據已經擷取的有效cookies來擷取目標連結的內容 /// </SUMMARY> /// <PARAM name="strUri">目標連結的url</PARAM> ///<PARAM name="post">post的byte資訊</PARAM> /// <PARAM name="ccl">已經擷取到的有效cookies</PARAM> /// <PARAM name="rppt">頭屬性的相關設定</PARAM> /// <RETURNS>目標串連的純文字:"txt/html"</RETURNS> public static string GetHtmlByCookies(string strUri, byte[] post, CookieCollection ccl, RequestParam rppt) { CookieContainer cc = new CookieContainer(); HttpWebRequest hwRequest; HttpWebResponse hwResponse; //構建即將發送的包頭 hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(strUri)); cc.Add(ccl); hwRequest.CookieContainer = cc; hwRequest.Accept = rppt.Accept; hwRequest.ContentType = rppt.ContentType; hwRequest.UserAgent = rppt.UserAgent; hwRequest.Method = rppt.Method; hwRequest.ContentLength = post.Length; //寫入post資訊 Stream stream; stream = hwRequest.GetRequestStream(); stream.Write(post, 0, post.Length); stream.Close(); //發送請求擷取響應內容 try { hwResponse = (HttpWebResponse)hwRequest.GetResponse(); } catch { return ""; } stream = hwResponse.GetResponseStream(); StreamReader sReader = new StreamReader(stream, Encoding.Default); string strHtml = sReader.ReadToEnd(); sReader.Close(); stream.Close(); //傳回值 return strHtml; } /// <summary> /// 根據泛型來構建字串用於post /// </summary> /// <param name="dir">帶有索引值對的泛型</param> /// <returns>構建完畢的字串</returns> public static byte[] CreatePostData(Dictionary<string, string> dir) { StringBuilder strPost = new StringBuilder(); foreach (KeyValuePair<string, string> kvp in dir) { strPost.Append(kvp.Key); strPost.Append('='); if (!string.IsNullOrWhiteSpace(kvp.Value)) { strPost.Append(System.Web.HttpUtility.UrlEncode(kvp.Value)); } strPost.Append('&'); } return CreatePostData(strPost.ToString().TrimEnd('&')); } public static byte[] CreatePostData(string input) { return Encoding.Default.GetBytes(input); } /// <summary> /// 向指定uri發起GET請求 /// </summary> /// <param name="uri"></param> /// <param name="request"></param> /// <returns></returns> public static string GET(string url) { WebClient wc = new WebClient(); wc.Encoding = System.Text.Encoding.UTF8; string s = wc.DownloadString(url); s = HttpUtility.UrlDecode(s); return s; } } /// <summary> /// 有關HTTP請求的輔助類 /// </summary> public class HttpWebResponseUtility { private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; /// <summary> /// 建立GET方式的HTTP請求 /// </summary> /// <param name="url">請求的URL</param> /// <param name="timeout">請求的逾時時間</param> /// <param name="userAgent">請求的用戶端瀏覽器資訊,可以為空白</param> /// <param name="cookies">隨同HTTP請求發送的Cookie資訊,如果不需要身分識別驗證可以為空白</param> /// <returns></returns> public static HttpWebResponse CreateGetHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } StringBuilder buffer = new StringBuilder(); if (!(parameters == null || parameters.Count == 0)) { int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); } i++; } } if (buffer.Length > 1) { url = url + "?" + buffer.ToString(); } url = HttpUtility.UrlDecode(url); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.UserAgent = DefaultUserAgent; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } return request.GetResponse() as HttpWebResponse; } /// <summary> /// 建立POST方式的HTTP請求 /// </summary> /// <param name="url">請求的URL</param> /// <param name="parameters">隨同請求POST的參數名稱及參數值字典</param> /// <param name="timeout">請求的逾時時間</param> /// <param name="userAgent">請求的用戶端瀏覽器資訊,可以為空白</param> /// <param name="requestEncoding">發送HTTP請求時所用的編碼</param> /// <param name="cookies">隨同HTTP請求發送的Cookie資訊,如果不需要身分識別驗證可以為空白</param> /// <returns></returns> public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //如果是發送HTTPS請求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; // request.ContentType = "application/x-www-form-urlencoded"; request.ContentType = "application/json"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST資料 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); } i++; } byte[] data = requestEncoding.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //總是接受 } public static string PostXml(string url, string xml) { byte[] bytes = Encoding.UTF8.GetBytes(xml); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentLength = bytes.Length; request.ContentType = "text/xml"; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode); throw new ApplicationException(message); } System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); string res = sr.ReadToEnd(); sr.Close(); response.Close(); return res; } }}
調用
string requestUrl = CoreInterface.ApiDomain + "api/Login/AddQRLog?grid={0}&ad={1}&grName={2}&vc={3}&br={4}&sc={5}&ts={6}&ps={7}"; requestUrl = string.Format(requestUrl, grid, ad, grName, vc, br, sc, ts, ps); string resultJson = ""; //try //{ HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(requestUrl, null, 1000000, "", null, null); System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()); resultJson = sr.ReadToEnd(); sr.Close(); //} //catch (Exception) //{ // return RedirectToAction("Index", "Error"); //}
C# 內建JSON轉換類
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Runtime.Serialization.Json;namespace AirMedia.Wap.Core{ public static class JsonHelper { #region DataContractJsonSerializer /// <summary> /// 對象轉換成json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonObject">需要格式化的對象</param> /// <returns>Json字串</returns> public static string DataContractJsonSerialize<T>(T jsonObject) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); string json = null; using (MemoryStream ms = new MemoryStream()) //定義一個stream用來存發序列化之後的內容 { serializer.WriteObject(ms, jsonObject); json = Encoding.UTF8.GetString(ms.GetBuffer()); //將stream讀取成一個字串形式的資料,並且返回 ms.Close(); } return json; } /// <summary> /// json字串轉換成對象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json">要轉換成對象的json字串</param> /// <returns></returns> public static T DataContractJsonDeserialize<T>(string json) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); T obj = default(T); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { obj = (T)serializer.ReadObject(ms); ms.Close(); } return obj; } #endregion }}