代码
using System;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace blogdata.nms_common
{
///
///定义获得数据流接口
///
public interface IRequestable
{
Stream GetStream(string requestUrl);
}
///
/// Http 的摘要说明
///
public class Http : IRequestable
{
///
///设置请求的延时时间,以秒为单位
///
private int mTimeOut = 1;
///
/// ̉异常错误信息
///
public string errorMessage;
public string ErrorMessage
{
get {return this.errorMessage;}
}
///
///构造函数
///
public Http(int timeOut)
{
this.mTimeOut = timeOut * 1000;
}
///
///用方法隐藏成员
///
///
///
public static Http GetIntance(int timeOut)
{
return new Http(timeOut);
}
///
///重载用方法隐藏成员,默认为1秒
///
public static Http GetIntance()
{
return new Http(1);
}
#region IRequestface ³ÉÔ±
///
///实现接口
///
///
///
public Stream GetStream(string requestUrl)
{
return GetStream(requestUrl,null);
}
///
///重载接口
///
///
///
///
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://标志,否则不能访问