C#登錄網站實際上就是模擬瀏覽器提交表單,然後記錄瀏覽器響應返回的會話Cookie值,再次發送請求時帶著這個會話cookie值去請求就可以實現模擬登錄的效果了。 如下類CookieAwareWebClient實現在發送請求時都帶著cookie。 如下是模擬表單提交登錄的使用示例: 推薦:http:/ ...
C#登錄網站實際上就是模擬瀏覽器提交表單,然後記錄瀏覽器響應返回的會話Cookie值,再次發送請求時帶著這個會話cookie值去請求就可以實現模擬登錄的效果了。
如下類CookieAwareWebClient實現在發送請求時都帶著cookie。
public class CookieAwareWebClient : WebClient {/* 何問起 hwq2.com */ private CookieContainer cookie = new CookieContainer(); protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = cookie; } return request; } }/* 何問起 hovertree.com */
如下是模擬表單提交登錄的使用示例:
var client = new CookieAwareWebClient(); client.BaseAddress = @"https://hovertree.net/any/base/url/"; var loginData = new NameValueCollection(); loginData.Add("login", "YourLogin"); loginData.Add("password", "YourPassword"); client.UploadValues("login.php", "POST", loginData); //Now you are logged in and can request pages string htmlSource = client.DownloadString("index.php");/* 何問起 hwq2.com */
推薦:http://www.cnblogs.com/roucheng/p/csharpfetch.html