下面的代碼實現了與以前XMLHTTP類似的功能。代碼如下:
HttpSendData.aspx
HttpReceiveData.aspx
補充code:
private HttpWebRequest CreateRequest()
{
HttpWebRequest 請求=null;
// string aa=TxNetId();
請求=(HttpWebRequest)HttpWebRequest.Create(this._strUrl);//建立請求
請求.Accept = "*/*"; //接受任意檔案
請求.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"; // 類比使用IE在瀏覽
請求.AllowAutoRedirect = true;//這裡不允許302
請求.CookieContainer =comm.cookie;//cookie容器,
請求.Referer="http://bbs.tiexue.net"; //當前頁面的引用
//如果附帶cookie 就發送
if ( this._cookiePost !=null)
{
System.Uri u =new Uri(_strUrl);
//doenet處理cookie的bug:請求的伺服器和cookie的Host必須一直,否則不發送或擷取!
//這裡修改成一致!
foreach(System.Net.Cookie c in _cookiePost)
{
c.Domain= u.Host;
}
請求.CookieContainer.Add(_cookiePost);
}
//如果需要發送資料,就以Post方式發送
if (_strPostdata !=null && _strPostdata.Length>0)
{
// 請求.CookieContainer.Add(new Cookie("TxNet","","/","bbs.tiexue.net"));
請求.ContentType = "application/x-www-form-urlencoded";//作為表單請求
請求.Method = "POST";//方式就是Post
//發送http資料:朝請求流中寫post的資料
byte[] b= this._encoding.GetBytes(this._strPostdata);
請求.ContentLength=b.Length;
System.IO.Stream sw=null;
try
{
sw=請求.GetRequestStream();
sw.Write(b,0,b.Length );
}
catch (System.Exception ex)
{
this._strErr=ex.Message;
}
finally
{
if (sw!=null){sw.Close();}
}
}
return 請求; //返回建立的請求對象
}
public string Proc()
{
HttpWebRequest 請求=CreateRequest();//請求
HttpWebResponse 響應=null;;
System.IO.StreamReader sr=null;
try
{
//這裡得到響應
響應 =(HttpWebResponse)請求.GetResponse();
sr=new System.IO.StreamReader(響應.GetResponseStream(),this.encoding);
this._ResHtml=sr.ReadToEnd(); // 這裡假定響應的都是html文本
}
catch (System.Exception ex)
{
this._strErr=ex.Message;//發生錯誤就返回空文本
return "";
}
finally
{
if (sr!=null){sr.Close();}
}
//狀態代碼
this._strCode=響應.StatusCode.ToString();
if (this._strCode=="302") //如果是302重新導向的話就返回新的地址。
{
this._ResHtml=響應.Headers["location"];
}
//得到cookie
if( 響應.Cookies.Count > 0)
{
this._cookieGet =響應.Cookies; //得到新的cookie:注意這裡沒考慮cookie合并的情況
}
return this.ResHtml ;
}