歡迎大家使用,寫了這麼久終於可以發布一個版本了。大家快下載試試吧。
功能說明:
1.實現常規的POST和GET請求。
2.實現了可設置編碼與無視編碼功能,可以自動解析編碼。
3.實現了Cookie攜帶功能。
4.實現了代理請求功能
5.更多的例子請大家到我博客查看
發一部分代碼給大家看吧
[csharp]
/// <summary>
/// 類說明:HttpHelps類,用來實現Http訪問,Post或者Get方式的,直接訪問,帶Cookie的,帶證書的等方式,可以設置代理
/// 編碼日期:2011-09-20
/// 編 碼 人:蘇飛
/// 聯系方式:361983679 Blogs:http://www.cckan.net
/// 修改日期:2012-09-20
/// </summary>
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO; www.2cto.com
using System.Text.RegularExpressions;
using System.IO.Compression;
namespace ImportZhiLian.FunctionServices
{
public class httphelper
{
#region 預定義方法或者變更
//默認的編碼
public Encoding encoding = Encoding.Default;
//HttpWebRequest對象用來發起請求
public HttpWebRequest request = null;
//獲取影響流的數據對象
private HttpWebResponse response = null;
//返回的Cookie
public string cookie = "";
//是否設置為全文小寫
public Boolean isToLower = true;
//讀取流的對象
private StreamReader reader = null;
//需要返回的數據對象
private string returnData = "String Error";
/// <summary>
/// 根據相傳入的數據,得到相應頁面數據
/// </summary>
/// <param name="strPostdata">傳入的數據Post方式,get方式傳NUll或者空字符串都可以</param>
/// <returns>string類型的響應數據</returns>
private string GetHttpRequestData(string strPostdata)
{
try
{
//支持跳轉頁面,查詢結果將是跳轉後的頁面
request.AllowAutoRedirect = true;
//驗證在得到結果時是否有傳入數據
if (!string.IsNullOrEmpty(strPostdata) && request.Method.Trim().ToLower().Contains("post"))
{
byte[] buffer = encoding.GetBytes(strPostdata);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
////最大連接數
//request.ServicePoint.ConnectionLimit = 1024;
#region 得到請求的response
using (response = (HttpWebResponse)request.GetResponse())
{
try
{
cookie = response.Headers["set-cookie"].ToString();
}
catch (Exception)
{
}
//從這裡開始我們要無視編碼了
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);
//.net4.0以下寫法
_stream = GetMemoryStream(response.GetResponseStream());
}
else
{
//response.GetResponseStream().CopyTo(_stream, 10240);
// .net4.0以下寫法
_stream = GetMemoryStream(response.GetResponseStream());
}
byte[] RawResponse = _stream.ToArray();
string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
//<meta(.*?)charset([\s]?)=[^>](.*?)>
Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline);
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);
}
}
}
returnData = encoding.GetString(RawResponse);
}
else
{
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
{
//開始讀取流並設置編碼方式
using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
{
returnData = reader.ReadToEnd();
}
}
else
{
//開始讀取流並設置編碼方式
using (reader = new StreamReader(response.GetResponseStream(), encoding))
{
returnData = reader.ReadToEnd();
}
}
}
}
#endregion
}
catch (WebException ex)
{
//這裡是在發生異常時返回的錯誤信息
returnData = "String Error";
response = (HttpWebResponse)ex.Response;
}
if (isToLower)
{
returnData = returnData.ToLower();
}
return returnData;
}
/// <summary>
/// 4.0以下.net版本取水運
/// </summary>
/// <param name="streamResponse"></param>
private static MemoryStream GetMemoryStream(Stream streamResponse)
{
MemoryStream _stream = new MemoryStream();
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = streamResponse.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
_stream.Write(buffer, 0, bytesRead);
bytesRead = streamResponse.Read(buffer, 0, Length);
}
return _stream;
}
/// <summary>
/// 為請求准備參數
/// </summary>
///<param name="objhttpItem">參數列表</param>
/// <param name="_Encoding">讀取數據時的編碼方式</param>
private void SetRequest(HttpItem objhttpItem)
{
//初始化對像,並設置請求的URL地址
request = (HttpWebRequest)WebRequest.Create(GetUrl(objhttpItem.URL));
//請求方式Get或者Post
request.Method = objhttpItem.Method;
//Accept
request.Accept = objhttpItem.Accept;
//ContentType返回類型
request.ContentType = objhttpItem.ContentType;
//UserAgent客戶端的訪問類型,包括浏覽器版本和操作系統信息
request.UserAgent = objhttpItem.UserAgent;
if (objhttpItem.Encoding == "NULL")
{
//讀取數據時的編碼方式
encoding = null;
}
else
{
//讀取數據時的編碼方式
encoding = System.Text.Encoding.GetEncoding(objhttpItem.Encoding);
}
//Cookie
request.Headers[HttpRequestHeader.Cookie] = objhttpItem.Cookie;
//來源地址
request.Referer = objhttpItem.Referer;
}
/// <summary>
/// 設置當前訪問使用的代理
/// </summary>
/// <param name="userName">代理 服務器用戶名</param>
/// <param name="passWord">代理 服務器密碼</param>
/// <param name="ip">代理 服務器地址</param>
public void SetWebProxy(string userName, string passWord, string ip)
{
//設置代理服務器
WebProxy myProxy = new WebProxy(ip, false);
//建議連接
myProxy.Credentials = new NetworkCredential(userName, passWord);
//給當前請求對象
request.Proxy = myProxy;
//設置安全憑證
request.Credentials = CredentialCache.DefaultNetworkCredentials;
}
#endregion
#region 普通類型
/// <summary>
/// 傳入一個正確或不正確的URl,返回正確的URL
/// </summary>
/// <param name="URL">url</param>
/// <returns>
/// </returns>
public static string GetUrl(string URL)
{
if (!(URL.Contains("http://") || URL.Contains("https://")))
{
URL = "http://" + URL;
}
return URL;
}
///<summary>
///采用https協議訪問網絡,根據傳入的URl地址,得到響應的數據字符串。
///</summary>
///<param name="objhttpItem">參數列表</param>
///<returns>String類型的數據</returns>
public string GetHtml(HttpItem objhttpItem)
{
//准備參數
SetRequest(objhttpItem);
//調用專門讀取數據的類
return GetHttpRequestData(objhttpItem.Postdata);
}
#endregion
}
/// <summary>
/// Http請求參考類
/// </summary>
public class HttpItem
{
string _URL;
/// <summary>
/// 請求URL必須填寫
/// </summary>
public string URL
{
get { return _URL; }
set { _URL = value; }
}
string _Method = "GET";
/// <summary>
/// 請求方式默認為GET方式
/// </summary>
public string Method
{
get { return _Method; }
set { _Method = value; }
}
string _Accept = "text/html, application/xhtml+xml, */*";
/// <summary>
/// 請求標頭值 默認為text/html, application/xhtml+xml, */*
/// </summary>
public string Accept
{
get { return _Accept; }
set { _Accept = value; }
}
string _ContentType = "text/html";
/// <summary>
/// 請求返回類型默認 text/html
/// </summary>
public string ContentType
{
get { return _ContentType; }
set { _ContentType = value; }
}
string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
/// <summary>
/// 客戶端訪問信息默認Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
/// </summary>
public string UserAgent
{
get { return _UserAgent; }
set { _UserAgent = value; }
}
string _Encoding = "NULL";
/// <summary>
/// 返回數據編碼默認為NUll,可以自動識別
/// </summary>
public string Encoding
{
get { return _Encoding; }
set { _Encoding = value; }
}
string _Postdata;
/// <summary>
/// Post請求時要發送的Post數據
/// </summary>
public string Postdata
{
get { return _Postdata; }
set { _Postdata = value; }
}
string _Cookie;
/// <summary>
/// 請求時的Cookie
/// </summary>
public string Cookie
{
get { return _Cookie; }
set { _Cookie = value; }
}
string _Referer;
/// <summary>
/// 來源地址,上次訪問地址
/// </summary>
public string Referer
{
get { return _Referer; }
set { _Referer = value; }
}
}
}
/// <summary>
/// 類說明:HttpHelps類,用來實現Http訪問,Post或者Get方式的,直接訪問,帶Cookie的,帶證書的等方式,可以設置代理
/// 編碼日期:2011-09-20
/// 編 碼 人:蘇飛
/// 聯系方式:361983679 Blogs:http://www.cckan.net
/// 修改日期:2012-09-20
/// </summary>
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;
namespace ImportZhiLian.FunctionServices
{
public class httphelper
{
#region 預定義方法或者變更
//默認的編碼
public Encoding encoding = Encoding.Default;
//HttpWebRequest對象用來發起請求
public HttpWebRequest request = null;
//獲取影響流的數據對象
private HttpWebResponse response = null;
//返回的Cookie
public string cookie = "";
//是否設置為全文小寫
public Boolean isToLower = true;
//讀取流的對象
private StreamReader reader = null;
//需要返回的數據對象
private string returnData = "String Error";
/// <summary>
/// 根據相傳入的數據,得到相應頁面數據
/// </summary>
/// <param name="strPostdata">傳入的數據Post方式,get方式傳NUll或者空字符串都可以</param>
/// <returns>string類型的響應數據</returns>
private string GetHttpRequestData(string strPostdata)
{
try
{
//支持跳轉頁面,查詢結果將是跳轉後的頁面
request.AllowAutoRedirect = true;
//驗證在得到結果時是否有傳入數據
if (!string.IsNullOrEmpty(strPostdata) && request.Method.Trim().ToLower().Contains("post"))
{
byte[] buffer = encoding.GetBytes(strPostdata);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
////最大連接數
//request.ServicePoint.ConnectionLimit = 1024;
#region 得到請求的response
using (response = (HttpWebResponse)request.GetResponse())
{
try
{
cookie = response.Headers["set-cookie"].ToString();
}
catch (Exception)
{
}
//從這裡開始我們要無視編碼了
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);
//.net4.0以下寫法
_stream = GetMemoryStream(response.GetResponseStream());
}
else
{
//response.GetResponseStream().CopyTo(_stream, 10240);
// .net4.0以下寫法
_stream = GetMemoryStream(response.GetResponseStream());
}
byte[] RawResponse = _stream.ToArray();
string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
//<meta(.*?)charset([\s]?)=[^>](.*?)>
Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline);
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);
}
}
}
returnData = encoding.GetString(RawResponse);
}
else
{
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
{
//開始讀取流並設置編碼方式
using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
{
returnData = reader.ReadToEnd();
}
}
else
{
//開始讀取流並設置編碼方式
using (reader = new StreamReader(response.GetResponseStream(), encoding))
{
returnData = reader.ReadToEnd();
}
}
}
}
#endregion
}
catch (WebException ex)
{
//這裡是在發生異常時返回的錯誤信息
returnData = "String Error";
response = (HttpWebResponse)ex.Response;
}
if (isToLower)
{
returnData = returnData.ToLower();
}
return returnData;
}
/// <summary>
/// 4.0以下.net版本取水運
/// </summary>
/// <param name="streamResponse"></param>
private static MemoryStream GetMemoryStream(Stream streamResponse)
{
MemoryStream _stream = new MemoryStream();
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = streamResponse.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
_stream.Write(buffer, 0, bytesRead);
bytesRead = streamResponse.Read(buffer, 0, Length);
}
return _stream;
}
/// <summary>
/// 為請求准備參數
/// </summary>
///<param name="objhttpItem">參數列表</param>
/// <param name="_Encoding">讀取數據時的編碼方式</param>
private void SetRequest(HttpItem objhttpItem)
{
//初始化對像,並設置請求的URL地址
request = (HttpWebRequest)WebRequest.Create(GetUrl(objhttpItem.URL));
//請求方式Get或者Post
request.Method = objhttpItem.Method;
//Accept
request.Accept = objhttpItem.Accept;
//ContentType返回類型
request.ContentType = objhttpItem.ContentType;
//UserAgent客戶端的訪問類型,包括浏覽器版本和操作系統信息
request.UserAgent = objhttpItem.UserAgent;
if (objhttpItem.Encoding == "NULL")
{
//讀取數據時的編碼方式
encoding = null;
}
else
{
//讀取數據時的編碼方式
encoding = System.Text.Encoding.GetEncoding(objhttpItem.Encoding);
}
//Cookie
request.Headers[HttpRequestHeader.Cookie] = objhttpItem.Cookie;
//來源地址
request.Referer = objhttpItem.Referer;
}
/// <summary>
/// 設置當前訪問使用的代理
/// </summary>
/// <param name="userName">代理 服務器用戶名</param>
/// <param name="passWord">代理 服務器密碼</param>
/// <param name="ip">代理 服務器地址</param>
public void SetWebProxy(string userName, string passWord, string ip)
{
//設置代理服務器
WebProxy myProxy = new WebProxy(ip, false);
//建議連接
myProxy.Credentials = new NetworkCredential(userName, passWord);
//給當前請求對象
request.Proxy = myProxy;
//設置安全憑證
request.Credentials = CredentialCache.DefaultNetworkCredentials;
}
#endregion
#region 普通類型
/// <summary>
/// 傳入一個正確或不正確的URl,返回正確的URL
/// </summary>
/// <param name="URL">url</param>
/// <returns>
/// </returns>
public static string GetUrl(string URL)
{
if (!(URL.Contains("http://") || URL.Contains("https://")))
{
URL = "http://" + URL;
}
return URL;
}
///<summary>
///采用https協議訪問網絡,根據傳入的URl地址,得到響應的數據字符串。
///</summary>
///<param name="objhttpItem">參數列表</param>
///<returns>String類型的數據</returns>
public string GetHtml(HttpItem objhttpItem)
{
//准備參數
SetRequest(objhttpItem);
//調用專門讀取數據的類
return GetHttpRequestData(objhttpItem.Postdata);
}
#endregion
}
/// <summary>
/// Http請求參考類
/// </summary>
public class HttpItem
{
string _URL;
/// <summary>
/// 請求URL必須填寫
/// </summary>
public string URL
{
get { return _URL; }
set { _URL = value; }
}
string _Method = "GET";
/// <summary>
/// 請求方式默認為GET方式
/// </summary>
public string Method
{
get { return _Method; }
set { _Method = value; }
}
string _Accept = "text/html, application/xhtml+xml, */*";
/// <summary>
/// 請求標頭值 默認為text/html, application/xhtml+xml, */*
/// </summary>
public string Accept
{
get { return _Accept; }
set { _Accept = value; }
}
string _ContentType = "text/html";
/// <summary>
/// 請求返回類型默認 text/html
/// </summary>
public string ContentType
{
get { return _ContentType; }
set { _ContentType = value; }
}
string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
/// <summary>
/// 客戶端訪問信息默認Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
/// </summary>
public string UserAgent
{
get { return _UserAgent; }
set { _UserAgent = value; }
}
string _Encoding = "NULL";
/// <summary>
/// 返回數據編碼默認為NUll,可以自動識別
/// </summary>
public string Encoding
{
get { return _Encoding; }
set { _Encoding = value; }
}
string _Postdata;
/// <summary>
/// Post請求時要發送的Post數據
/// </summary>
public string Postdata
{
get { return _Postdata; }
set { _Postdata = value; }
}
string _Cookie;
/// <summary>
/// 請求時的Cookie
/// </summary>
public string Cookie
{
get { return _Cookie; }
set { _Cookie = value; }
}
string _Referer;
/// <summary>
/// 來源地址,上次訪問地址
/// </summary>
public string Referer
{
get { return _Referer; }
set { _Referer = value; }
}
}
}