新建Common類庫 ...
新建Common類庫
/// <summary> /// string的擴展 /// </summary> public static class StringExt { /// <summary> /// 格式清理 轉義"\" 去掉{}<>#$等特殊字元 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string FormatClear(this string text) { text = text.Replace("\n\t\t\t\t\t", "") .Replace("\n\r", "\\n\\r") .Replace("\r\n", "\\r\\n") .Replace("\r", "\\r") .Replace("\t", "") .Replace("\n", "\\n") .Replace("{", "") .Replace("}", "") .Replace("<", "") .Replace(">", "") .Replace(",", ",") .Replace(":", ":") .Replace("\"", "\\\"") .Replace("#", "") .Replace("%", "") .Replace("$", "") .Replace("^", "") .Replace("*", ""); return text; } }
/// <summary> /// web請求擴展 /// </summary> public static class WebRequestExt { /// <summary> /// Get方式發起請求 返回處理結果 (HttpWebRequest提交Get信息) /// </summary> /// <param name="url">請求地址</param> /// <returns></returns> public static string GetData(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retstring = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retstring; } /// <summary> /// Post方式帶參數發起請求 返回處理結果 (HttpWebRequest提交POST信息) /// </summary> /// <param name="jsonData">請求的參數-json格式</param> /// <param name="url">請求的地址</param> /// <returns></returns> public static string PostData(string jsonData, string url) { //將提交的字元串數據轉換成位元組數組 byte[] postData = Encoding.UTF8.GetBytes(jsonData); //設置提交的相關參數 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //提交方式 request.Method = "POST"; //編碼格式 request.ContentType = "text/html;charset=UTF-8"; request.ContentLength = postData.Length; // 提交請求數據 Stream outputStream = request.GetRequestStream(); outputStream.Write(postData, 0, postData.Length); outputStream.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.Default); string srcString = reader.ReadToEnd(); reader.Close(); responseStream.Close(); outputStream.Close(); return srcString; } }