public class WebHelper
{
#region ResolveUrl(解析相对Url)
/// <summary>
/// 解析相对Url
/// </summary>
/// <param name="relativeUrl">相对Url</param>
public static string ResolveUrl(string relativeUrl)
{
if (string.IsNullOrWhiteSpace(relativeUrl))
return string.Empty;
relativeUrl = relativeUrl.Replace("\\", "/");
if (relativeUrl.StartsWith("/"))
return relativeUrl;
if (relativeUrl.Contains("://"))
return relativeUrl;
return VirtualPathUtility.ToAbsolute(relativeUrl);
}
#endregion
#region HtmlEncode(对html字符串进行编码)
/// <summary>
/// 对html字符串进行编码
/// </summary>
/// <param name="html">html字符串</param>
public static string HtmlEncode(string html)
{
return HttpUtility.HtmlEncode(html);
}
/// <summary>
/// 对html字符串进行解码
/// </summary>
/// <param name="html">html字符串</param>
public static string HtmlDecode(string html)
{
return HttpUtility.HtmlDecode(html);
}
#endregion
#region UrlEncode(对Url进行编码)
/// <summary>
/// 对Url进行编码
/// </summary>
/// <param name="url">url</param>
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
public static string UrlEncode(string url, bool isUpper = false)
{
return UrlEncode(url, Encoding.UTF8, isUpper);
}
/// <summary>
/// 对Url进行编码
/// </summary>
/// <param name="url">url</param>
/// <param name="encoding">字符编码</param>
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
{
var result = HttpUtility.UrlEncode(url, encoding);
if (!isUpper)
return result;
return GetUpperEncode(result);
}
/// <summary>
/// 获取大写编码字符串
/// </summary>
private static string GetUpperEncode(string encode)
{
var result = new StringBuilder();
int index = int.MinValue;
for (int i = 0; i < encode.Length; i++)
{
string character = encode[i].ToString();
if (character == "%")
index = i;
if (i - index == 1 || i - index == 2)
character = character.ToUpper();
result.Append(character);
}
return result.ToString();
}
#endregion
#region UrlDecode(对Url进行解码)
/// <summary>
/// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
/// </summary>
/// <param name="url">url</param>
public static string UrlDecode(string url)
{
return HttpUtility.UrlDecode(url);
}
/// <summary>
/// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
/// </summary>
/// <param name="url">url</param>
/// <param name="encoding">字符编码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码</param>
public static string UrlDecode(string url, Encoding encoding)
{
return HttpUtility.UrlDecode(url, encoding);
}
#endregion
#region Session操作
/// <summary>
/// 写Session
/// </summary>
/// <typeparam name="T">Session键值的类型</typeparam>
/// <param name="key">Session的键名</param>
/// <param name="value">Session的键值</param>
public static void WriteSession<T>(string key, T value)
{
if (key.IsEmpty())
return;
HttpContext.Current.Session[key] = value;
}
/// <summary>
/// 写Session
/// </summary>
/// <param name="key">Session的键名</param>
/// <param name="value">Session的键值</param>
public static void WriteSession(string key, string value)
{
WriteSession<string>(key, value);
}
/// <summary>
/// 读取Session的值
/// </summary>
/// <param name="key">Session的键名</param>
public static string GetSession(string key)
{
if (key.IsEmpty())
return string.Empty;
return HttpContext.Current.Session[key] as string;
}
/// <summary>
/// 删除指定Session
/// </summary>
/// <param name="key">Session的键名</param>
public static void RemoveSession(string key)
{
if (key.IsEmpty())
return;
HttpContext.Current.Session.Contents.Remove(key);
}
#endregion
#region Cookie操作
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string strValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(cookie);
}
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
/// <param name="strValue">过期时间(分钟)</param>
public static void WriteCookie(string strName, string strValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
/// <summary>
/// 删除Cookie对象
/// </summary>
/// <param name="CookiesName">Cookie对象名称</param>
public static void RemoveCookie(string CookiesName)
{
HttpCookie objCookie = new HttpCookie(CookiesName.Trim());
objCookie.Expires = DateTime.Now.AddYears(-5);
HttpContext.Current.Response.Cookies.Add(objCookie);
}
#endregion
#region GetFileControls(获取客户端文件控件集合)
/// <summary>
/// 获取有效客户端文件控件集合,文件控件必须上传了内容,为空将被忽略,
/// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
/// </summary>
public static List<HttpPostedFile> GetFileControls()
{
var result = new List<HttpPostedFile>();
var files = HttpContext.Current.Request.Files;
if (files.Count == 0)
return result;
for (int i = 0; i < files.Count; i++)
{
var file = files[i];
if (file.ContentLength == 0)
continue;
result.Add(files[i]);
}
return result;
}
#endregion
#region GetFileControl(获取第一个有效客户端文件控件)
/// <summary>
/// 获取第一个有效客户端文件控件,文件控件必须上传了内容,为空将被忽略,
/// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
/// </summary>
public static HttpPostedFile GetFileControl()
{
var files = GetFileControls();
if (files == null || files.Count == 0)
return null;
return files[0];
}
#endregion
#region HttpWebRequest(请求网络资源)
/// <summary>
/// 请求网络资源,返回响应的文本
/// </summary>
/// <param name="url">网络资源地址</param>
public static string HttpWebRequest(string url)
{
return HttpWebRequest(url, string.Empty, Encoding.GetEncoding("utf-8"));
}
/// <summary>
/// 请求网络资源,返回响应的文本
/// </summary>
/// <param name="url">网络资源Url地址</param>
/// <param name="parameters">提交的参数,格式:参数1=参数值1&参数2=参数值2</param>
public static string HttpWebRequest(string url, string parameters)
{
return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), true);
}
/// <summary>
/// 请求网络资源,返回响应的文本
/// </summary>
/// <param name="url">网络资源地址</param>
/// <param name="parameters">提交的参数,格式:参数1=参数值1&参数2=参数值2</param>
/// <param name="encoding">字符编码</param>
/// <param name="isPost">是否Post提交</param>
/// <param name="contentType">内容类型</param>
/// <param name="cookie">Cookie容器</param>
/// <param name="timeout">超时时间</param>
public static string HttpWebRequest(string url, string parameters, Encoding encoding, bool isPost = false,
string contentType = "application/x-www-form-urlencoded", CookieContainer cookie = null, int timeout = 120000)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeout;
request.CookieContainer = cookie;
if (isPost)
{
byte[] postData = encoding.GetBytes(parameters);
request.Method = "POST";
request.ContentType = contentType;
request.ContentLength = postData.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(postData, 0, postData.Length);
}
}
var response = (HttpWebResponse)request.GetResponse();
string result;
using (Stream stream = response.GetResponseStream())
{
if (stream == null)
return string.Empty;
using (var reader = new StreamReader(stream, encoding))
{
result = reader.ReadToEnd();
}
}
return result;
}
#endregion
#region 去除HTML标记
/// <summary>
/// 去除HTML标记
/// </summary>
/// <param name="NoHTML">包括HTML的源码 </param>
/// <returns>已经去除后的文字</returns>
public static string NoHtml(string Htmlstring)
{
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"…", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"—", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"“", "", RegexOptions.IgnoreCase);
Htmlstring.Replace("<", "");
Htmlstring = Regex.Replace(Htmlstring, @"”", "", RegexOptions.IgnoreCase);
Htmlstring.Replace(">", "");
Htmlstring.Replace("\r\n", "");
Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
return Htmlstring;
}
#endregion
#region 格式化文本(防止SQL注入)
/// <summary>
/// 格式化文本(防止SQL注入)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Formatstr(string html)
{
System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
html = regex1.Replace(html, ""); //过滤<script></script>标记
html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
html = regex4.Replace(html, ""); //过滤iframe
html = regex10.Replace(html, "s_elect");
html = regex11.Replace(html, "u_pudate");
html = regex12.Replace(html, "d_elete");
html = html.Replace("'", "’");
html = html.Replace(" ", " ");
return html;
}
#endregion
#region 客户端信息
/// <summary>
/// 是否是get请求
/// </summary>
/// <returns></returns>
public static bool IsGet()
{
return HttpContext.Current.Request.HttpMethod == "GET";
}
/// <summary>
/// 是否是post请求
/// </summary>
/// <returns></returns>
public static bool IsPost()
{
return HttpContext.Current.Request.HttpMethod == "POST";
}
/// <summary>
/// 是否是Ajax请求
/// </summary>
/// <returns></returns>
public static bool IsAjax()
{
return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
/// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static string GetQueryString(string key, string defaultValue)
{
string value = HttpContext.Current.Request.QueryString[key];
if (!string.IsNullOrWhiteSpace(value))
return value;
else
return defaultValue;
}
/// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static string GetQueryString(string key)
{
return GetQueryString(key, "");
}
/// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int GetQueryInt(string key, int defaultValue)
{
return TypeHelper.StringToInt(HttpContext.Current.Request.QueryString[key], defaultValue);
}
/// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static int GetQueryInt(string key)
{
return GetQueryInt(key, 0);
}
/// <summary>
/// 如果是GET请求,则从查询字符串中获取值;如果是POST则从表单中获取值。
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetParamValue(string key)
{
if (IsGet())
return GetQueryString(key);
else
return GetFormString(key);
}
public static string GetHeadersParamValue(string key)
{
var requestHeader = HttpContext.Current.Request.Headers;
return requestHeader.Get(key);
}
/// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static string GetFormString(string key, string defaultValue)
{
string value = HttpContext.Current.Request.Form[key];
if (!string.IsNullOrWhiteSpace(value))
return value;
else
return defaultValue;
}
/// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static string GetFormString(string key)
{
return GetFormString(key, "");
}
/// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int GetFormInt(string key, int defaultValue)
{
return TypeHelper.StringToInt(HttpContext.Current.Request.Form[key], defaultValue);
}
/// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static int GetFormInt(string key)
{
return GetFormInt(key, 0);
}
/// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static string GetRequestString(string key, string defaultValue)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormString(key, defaultValue);
else
return GetQueryString(key, defaultValue);
}
/// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static string GetRequestString(string key)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormString(key);
else
return GetQueryString(key);
}
/// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int GetRequestInt(string key, int defaultValue)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormInt(key, defaultValue);
else
return GetQueryInt(key, defaultValue);
}
/// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static int GetRequestInt(string key)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormInt(key);
else
return GetQueryInt(key);
}
/// <summary>
/// 获得上次请求的url
/// </summary>
/// <returns></returns>
public static string GetUrlReferrer()
{
Uri uri = HttpContext.Current.Request.UrlReferrer;
if (uri == null)
return string.Empty;
return uri.ToString();
}
/// <summary>
/// 获得请求的主机部分
/// </summary>
/// <returns></returns>
public static string GetHost()
{
return HttpContext.Current.Request.Url.Host;
}
/// <summary>
/// 获得请求的url
/// </summary>
/// <returns></returns>
public static string GetUrl()
{
return HttpContext.Current.Request.Url.ToString();
}
/// <summary>
/// 获得请求的原始url
/// </summary>
/// <returns></returns>
public static string GetRawUrl()
{
return HttpContext.Current.Request.RawUrl;
}
/// <summary>
/// 获得请求的ip
/// </summary>
/// <returns></returns>
public static string GetIP()
{
string ip = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
if (string.IsNullOrEmpty(ip) || !ValidateHelper.IsIP(ip))
ip = "127.0.0.1";
return ip;
}
/// <summary>
/// 获得请求的浏览器类型
/// </summary>
/// <returns></returns>
public static string GetBrowserType()
{
string type = HttpContext.Current.Request.Browser.Type;
if (string.IsNullOrEmpty(type) || type == "unknown")
return "未知";
return type.ToLower();
}
/// <summary>
/// 获得请求的浏览器名称
/// </summary>
/// <returns></returns>
public static string GetBrowserName()
{
string name = HttpContext.Current.Request.Browser.Browser;
if (string.IsNullOrEmpty(name) || name == "unknown")
return "未知";
return name.ToLower();
}
/// <summary>
/// 获得请求的浏览器版本
/// </summary>
/// <returns></returns>
public static string GetBrowserVersion()
{
string version = HttpContext.Current.Request.Browser.Version;
if (string.IsNullOrEmpty(version) || version == "unknown")
return "未知";
return version;
}
/// <summary>
/// 获得请求客户端的操作系统类型
/// </summary>
/// <returns></returns>
public static string GetOSType()
{
string userAgent = HttpContext.Current.Request.UserAgent;
if (userAgent == null)
return "未知";
string type = null;
if (userAgent.Contains("NT 6.1"))
type = "Windows 7";
else if (userAgent.Contains("NT 5.1"))
type = "Windows XP";
else if (userAgent.Contains("NT 6.2"))
type = "Windows 8";
else if (userAgent.Contains("android"))
type = "Android";
else if (userAgent.Contains("iphone"))
type = "IPhone";
else if (userAgent.Contains("Mac"))
type = "Mac";
else if (userAgent.Contains("NT 6.0"))
type = "Windows Vista";
else if (userAgent.Contains("NT 5.2"))
type = "Windows 2003";
else if (userAgent.Contains("NT 5.0"))
type = "Windows 2000";
else if (userAgent.Contains("98"))
type = "Windows 98";
else if (userAgent.Contains("95"))
type = "Windows 95";
else if (userAgent.Contains("Me"))
type = "Windows Me";
else if (userAgent.Contains("NT 4"))
type = "Windows NT4";
else if (userAgent.Contains("Unix"))
type = "UNIX";
else if (userAgent.Contains("Linux"))
type = "Linux";
else if (userAgent.Contains("SunOS"))
type = "SunOS";
else
type = "未知";
return type;
}
/// <summary>
/// 获得请求客户端的操作系统名称
/// </summary>
/// <returns></returns>
public static string GetOSName()
{
string name = HttpContext.Current.Request.Browser.Platform;
if (string.IsNullOrEmpty(name))
return "未知";
return name;
}
/// <summary>
/// 判断是否是浏览器请求
/// </summary>
/// <returns></returns>
public static bool IsBrowser()
{
string name = GetBrowserName();
foreach (string item in _browserlist)
{
if (name.Contains(item))
return true;
}
return false;
}
/// <summary>
/// 是否是移动设备请求
/// </summary>
/// <returns></returns>
public static bool IsMobile()
{
string userAgent = HttpContext.Current.Request.UserAgent;
if (userAgent == null)
return false;
if ((_detectmobilebrowserregex_b.IsMatch(userAgent) || _detectmobilebrowserregex_v.IsMatch(userAgent.Substring(0, 4))))
return true;
return false;
}
/// <summary>
/// 判断是否是搜索引擎爬虫请求
/// </summary>
/// <returns></returns>
public static bool IsCrawler()
{
bool result = HttpContext.Current.Request.Browser.Crawler;
if (!result)
{
string referrer = GetUrlReferrer();
if (referrer.Length > 0)
{
foreach (string item in _searchenginelist)
{
if (referrer.Contains(item))
return true;
}
}
}
return result;
}
#endregion
#region Http
/// <summary>
/// 获得参数列表
/// </summary>
/// <param name="data">数据</param>
/// <returns></returns>
public static NameValueCollection GetParmList(string data)
{
NameValueCollection parmList = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(data))
{
int length = data.Length;
for (int i = 0; i < length; i++)
{
int startIndex = i;
int endIndex = -1;
while (i < length)
{
char c = data[i];
if (c == '=')
{
if (endIndex < 0)
endIndex = i;
}
else if (c == '&')
{
break;
}
i++;
}
string key;
string value;
if (endIndex >= 0)
{
key = data.Substring(startIndex, endIndex - startIndex);
value = data.Substring(endIndex + 1, (i - endIndex) - 1);
}
else
{
key = data.Substring(startIndex, i - startIndex);
value = string.Empty;
}
parmList[key] = value;
if ((i == (length - 1)) && (data[i] == '&'))
parmList[key] = string.Empty;
}
}
return parmList;
}
/// <summary>
/// 获得http请求数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="postData">发送数据</param>
/// <returns></returns>
public static string GetRequestData(string url, string postData)
{
return GetRequestData(url, "post", postData);
}
/// <summary>
/// 获得http请求数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="method">请求方式</param>
/// <param name="postData">发送数据</param>
/// <returns></returns>
public static string GetRequestData(string url, string method, string postData)
{
return GetRequestData(url, method, postData, Encoding.UTF8);
}
/// <summary>
/// 获得http请求数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="method">请求方式</param>
/// <param name="postData">发送数据</param>
/// <param name="encoding">编码</param>
/// <returns></returns>
public static string GetRequestData(string url, string method, string postData, Encoding encoding)
{
return GetRequestData(url, method, postData, encoding, 20000);
}
/// <summary>
/// 获得http请求数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="method">请求方式</param>
/// <param name="postData">发送数据</param>
/// <param name="encoding">编码</param>
/// <param name="timeout">超时值</param>
/// <returns></returns>
public static string GetRequestData(string url, string method, string postData, Encoding encoding, int timeout)
{
if (!(url.Contains("http://") || url.Contains("https://")))
url = "http://" + url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method.Trim().ToLower();
request.Timeout = timeout;
request.AllowAutoRedirect = true;
request.ContentType = "text/html";
request.Accept = "text/html, application/xhtml+xml, */*,zh-CN";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
try
{
if (!string.IsNullOrEmpty(postData) && request.Method == "post")
{
byte[] buffer = encoding.GetBytes(postData);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (encoding == null)
{
MemoryStream stream = new MemoryStream();
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(stream, 10240);
else
response.GetResponseStream().CopyTo(stream, 10240);
byte[] RawResponse = stream.ToArray();
string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
Match meta = _metaregex.Match(temp);
string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
charter = charter.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(";", string.Empty);
if (charter.Length > 0)
{
charter = charter.ToLower().Replace("iso-8859-1", "gbk");
encoding = Encoding.GetEncoding(charter);
}
else
{
if (response.CharacterSet.ToLower().Trim() == "iso-8859-1")
{
encoding = Encoding.GetEncoding("gbk");
}
else
{
if (string.IsNullOrEmpty(response.CharacterSet.Trim()))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
}
return encoding.GetString(RawResponse);
}
else
{
StreamReader reader = null;
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
{
using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
{
return reader.ReadToEnd();
}
}
else
{
using (reader = new StreamReader(response.GetResponseStream(), encoding))
{
try
{
return reader.ReadToEnd();
}
catch
{
return "close";
}
}
}
}
}
}
catch
{
return "error";
}
}
#endregion
}