c#向某網址Post資訊,並得到Cookies

smeller發表於2011-10-21
 

using System.Net;
using System.IO;
using System.Text;
[STAThread]
static void Main(string[] args)
{

string url="http://hi.baidu.com/yimeng3025/test.asp";

string indata="aa=zhuye";
string outdata="";
CookieContainer myCookieContainer=new CookieContainer();
字串8

//新建一個CookieContainer來存放Cookie集合
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(url);
//新建一個HttpWebRequest
myHttpWebRequest.ContentType="application/x-www-form-urlencoded";
myHttpWebRequest.ContentLength=indata.Length;
myHttpWebRequest.Method="POST";
myHttpWebRequest.CookieContainer=myCookieContainer;
//設定HttpWebRequest的CookieContainer為剛才建立的那個myCookieContainer
Stream myRequestStream=myHttpWebRequest.GetRequestStream();
StreamWriter myStreamWriter=new StreamWriter(myRequestStream,Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(indata);
//把資料寫入HttpWebRequest的Request流
myStreamWriter.Close();
myRequestStream.Close();
//關閉開啟物件
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
字串9

//新建一個HttpWebResponse
myHttpWebResponse.Cookies=myCookieContainer.GetCookies(myHttpWebRequest.RequestUri);
//獲取一個包含url的Cookie集合的CookieCollection
Stream myResponseStream=myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader=new StreamReader(myResponseStream,Encoding.GetEncoding("gb2312"));
outdata=myStreamReader.ReadToEnd();
//把資料從HttpWebResponse的Response流中讀出
myStreamReader.Close();
myResponseStream.Close();
Console.WriteLine(outdata);
//顯示"登入"

//拿到了Cookie,再進行請求就能直接讀取到登入後的內容了
myHttpWebRequest=(HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.CookieContainer=myCookieContainer;//*
//剛才那個CookieContainer已經存有了Cookie,把它附加到HttpWebRequest中則能直接通過驗證
myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
字串1


myHttpWebResponse.Cookies=myCookieContainer.GetCookies(myHttpWebRequest.RequestUri);
myResponseStream=myHttpWebResponse.GetResponseStream();
myStreamReader=new StreamReader(myResponseStream,Encoding.GetEncoding("gb2312"));
outdata=myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
Console.WriteLine(outdata);
//再次顯示"登入"
//如果把*行註釋調,就顯示"沒有登入"
}

相關文章