Re: [問題] 請問如何c#登入有帳號密碼的網頁 抓網괠…
我的做法
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("http://LoginUrl");
//上面的網址要自己查一下,通常是登入頁
webReq.CookieContainer = new CookieContainer(); //拿來裝Cookie的東西
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.Method = "POST";
string postString = "username=abc&password=123";
//該post的東西可能要自己查一下,可以用攔截封包的軟體來得知
byte[] postData = Encoding.ASCII.GetBytes(postString)
webReq.ContentLength = postData.Length;
Stream sm = webReq.GetRequestStream();
sm.Write(postData, 0, postData.Length);
sm.Close();
//取得回應
HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
//取得cookie
string cookie = webReq.CookieContainer.GetCookieHeader(webReq.RequestUri);
webResp.Close();
//再來建立你要取得的Request
webReq = (HttpWebRequest)WebRequest.Create("http://WhatYouWantToGet");
//將剛剛取得的cookie加上去
webReq.Headers.Add("cookie:" + cookie);
//取得回應
webResp = (HttpWebResponse)webReq.GetResponse();
//取得網站資料
Stream stream = webResp.GetResponseStream();
StreamReader sr = new StreamReader(stream, Encoding.Default);
//上面的編碼得自己判斷
String webData = sr.ReadToEnd();
webResp.Close();
之前在做的時候還有遇到一個問題
在取得cookie的時候伺服器會傳回417錯誤
如果有發生的話
在取得cookie之前把ServicePointManager.Expect100Continue設成false就行了
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.142.138.27
推
09/21 13:49, , 1F
09/21 13:49, 1F
→
06/18 11:15, , 2F
06/18 11:15, 2F
→
06/18 11:19, , 3F
06/18 11:19, 3F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
C_Sharp 近期熱門文章
PTT數位生活區 即時熱門文章
14
30