代碼
using System;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace blogdata.nms_common
{
///<summary>
///定義獲得資料流介面
///</summary>
public interface IRequestable
{
Stream GetStream(string requestUrl);
}
///<summary>
/// Http 的摘要說明
///</summary>
public class Http : IRequestable
{
///<summary>
///佈建要求的延時時間,以秒為單位
///</summary>
private int mTimeOut = 1;
///<summary>
/// ̉異常錯誤資訊
///</summary>
public string errorMessage;
public string ErrorMessage
{
get {return this.errorMessage;}
}
///<summary>
///建構函式
///</summary>
public Http(int timeOut)
{
this.mTimeOut = timeOut * 1000;
}
///<summary>
///用方法隱藏成員
///</summary>
///<param name="timeOut"></param>
///<returns></returns>
public static Http GetIntance(int timeOut)
{
return new Http(timeOut);
}
///<summary>
///重載用方法隱藏成員,預設為1秒
///</summary>
public static Http GetIntance()
{
return new Http(1);
}
#region IRequestface ³ÉÔ±
///<summary>
///實現介面
///</summary>
///<param name="requestUrl"></param>
///<returns></returns>
public Stream GetStream(string requestUrl)
{
return GetStream(requestUrl,null);
}
///<summary>
///重載介面
///</summary>
///<param name="requestUrl"></param>
///<param name="postData"></param>
///<returns></returns>
public Stream GetStream(string requestUrl,byte[] postData)
{
if (requestUrl == null || requestUrl.Length == 0) return null;
//判斷有沒有http://頭
string httpHead = requestUrl.Substring(0,7);
if (httpHead.ToLower() != "http://") return null;
WebRequest wrq = WebRequest.Create(requestUrl);
wrq.Timeout = this.mTimeOut; //請求的時間,以秒為單位
if (postData != null)
{
wrq.Method = "POST";
wrq.ContentType =
"application/x-www-form-urlencoded";
wrq.ContentLength = postData.Length;
Stream rs = wrq.GetRequestStream();
rs.Write(postData,0,postData.Length);
rs.Close();
rs = null;
}
try
{
WebResponse wrp = wrq.GetResponse();
Stream res = wrp.GetResponseStream();
if(res != null) return res;
}
catch (WebException we)
{
//調試使用,也可以轉化為流輸出,我沒有轉化
this.errorMessage = we.Message;
}
return null;
}
#endregion
}
}
調用方法:
Stream gets = Http.GetIntance(timeout).GetStream(url);
//這裡可以判斷一下流
if (gets == null)
Response.Write("error");
else
{
//由於有些網域名稱的訪問是返回了北京寬頻網或者其他的錯誤資訊。因此不能捕獲異常,結果為:流 !=null 通過讀出流看一下資料,就明白了。
Encoding encode =
System.Text.Encoding.GetEncoding("gb2312");
//讀流
StreamReader reader = new StreamReader(gets, encode);
string str = reader.ReadToEnd().ToString();
Response.Write(str);
}
註:
1、這裡就不要捕獲異常了。如果返回的為:null則就是發生了異常。因為我在類裡面
已經處理異常了。
2、Url必須為完整的路徑
即:帶有http://標誌,否則不能訪問