Asp.net XMLHTTP封装类(GET,Post发送和接收数据)

homehttp 2008-11-10

代码如下:

/**************************************************************** 
* 函数名称:SendCommand(SendMethod method, ST_Param p) 
* 功能说明:向远程发送URL和参数,接受返回信息(无乱码); 
* 参 数:method:xml发送方法,POST/Get 两种 
P:参数结构体 
public string Url; //远程URL 
public string Parameters; //参数 
public string Uid; //帐号 
public string Pwd; //号令 
* 调用示列: 
* using ebcnc; //引用空间名 
* XMLHTTP x = new XMLHTTP(); //创建设xmlhttp对像 
* XMLHTTP.ST_Param st = new XMLHTTP.ST_Param(); //创建参数数组 
* st.Parameters = ""; //url详细参数 
* st.Url = "http://www.baidu.com/"; //url 
* st.Uid = "" ; //帐号 
* st.Pwd = ""; //口令 
* string rn=””; //返回字符串 
* rn=x.SendCommand(XMLHTTP.SendMethod.POST, st); //获取返回信息 
* x.Dispose(); 

***********************************************************************/ 
using System; 
using MSXML2; 
namespace ebcnc 
{ 
/// <summary> 
/// XMLHTTP基类 
/// </summary> 
public class XMLHTTP : IDisposable 
{ 
#region 变量及参数 
private XMLHTTPClass xml; 
private bool _alreadyDispose = false; 

public ST_Param Parameters; 

public enum SendMethod : int 
{ 
POST, GET 
} 
#endregion 

#region 参数结构体 
public struct ST_Param 
{ 
public string Url; 
public string Parameters; 
public string Uid; 
public string Pwd; 
} 
#endregion 

#region 发送数据 
/// <summary> 
/// 发送数据 
/// </summary> 
/// <param name="method">发送方式</param> 
/// <param name="p">数据</param> 
/// <returns>STRING</returns> 
public virtual string SendCommand(SendMethod method, ST_Param p) 
{ 
if (p.Url == null || p.Url == "") return null; 
if (method == SendMethod.POST) 
{ 
try 
{ 
xml.open("POST", p.Url, false, p.Uid, p.Pwd); 
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
xml.send(CommonFunction.UrlEncoding(p.Parameters)); 
if (xml.status == 200) 
{ 
return System.Text.Encoding.Default.GetString((byte[])xml.responseBody); 
} 
else 
{ 
return xml.status.ToString(); 
} 
} 
catch (Exception E) 
{ 
return E.Message.ToString(); 
} 
} 
else if (method == SendMethod.GET) 
{ 
xml.open("GET", p.Url + "?" + CommonFunction.UrlEncoding(p.Parameters), false, p.Uid, p.Pwd); 
xml.send(null); 
return System.Text.Encoding.Default.GetString((byte[])xml.responseBody); 
} 
return null; 
} 
#endregion 

#region 构造与释构 
public XMLHTTP() 
{ 
xml = new XMLHTTPClass(); 
} 
~XMLHTTP() 
{ 
Dispose(); 
} 
protected virtual void Dispose(bool isDisposing) 
{ 
if (_alreadyDispose) return; 
if (isDisposing) 
{ 
if (xml != null) 
{ 
xml = null; 
} 
} 
_alreadyDispose = true; 
} 
#endregion 

#region IDisposable 成员 

public void Dispose() 
{ 
Dispose(true); 
GC.SuppressFinalize(this); 
} 

#endregion 
} 
}

相关推荐