代碼
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://標志,否則不能訪問
新聞熱點
疑難解答