新建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, , 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;
}
}
05-11 17:47