應用C#發送Http要求完成模仿上岸實例。本站提示廣大學習愛好者:(應用C#發送Http要求完成模仿上岸實例)文章只能為提供參考,不一定能成為您想要的結果。以下是應用C#發送Http要求完成模仿上岸實例正文
模仿上岸的道理很簡略,就是發送一個Http 要求辦事器取得呼應,然後客戶端獲得到cookie便可完成模仿上岸,好比一些搶票軟件的道理不過也是如許模仿客戶真個cookie 然後發送要求去搶票,然後12306 本文將演示若何用C# 來完成模仿上岸的,推舉一款對象Fiddler,這是一款監聽http 要求的利器。空話不多說,我就以博客園為例來完成模仿上岸。起首我上岸博客園 http://passport.cnblogs.com/login.aspx 輸出用戶名和暗碼點上岸 就會看到Fiddler 上的相干信息:

Ok,我起首須要發送一個http 要求 ,這個要求時POST的方法,然後用戶名和暗碼就是POST的數據。代碼以下:
static CookieContainer GetCookie(string postString, string postUrl)
{
CookieContainer cookie = new CookieContainer();
HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(postUrl);//創立http 要求
httpRequset.CookieContainer = cookie;//設置cookie
httpRequset.Method = "POST";//POST 提交
httpRequset.KeepAlive = true;
httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
httpRequset.Accept = "text/html, application/xhtml+xml, */*";
httpRequset.ContentType = "application/x-www-form-urlencoded";//以上信息在監聽要求的時刻都有的直接復制過去
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString);
httpRequset.ContentLength = bytes.Length;
Stream stream = httpRequset.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();//以上是POST數據的寫入
HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();//取得 辦事端呼應
return cookie;//拿到cookie
}
拿到cookie 以後我們便可以以用戶的甚麼去用戶的後台或許其他的處所:
static string GetContent(CookieContainer cookie, string url)
{
string content;
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.CookieContainer = cookie;
httpRequest.Referer = url;
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
httpRequest.Accept = "text/html, application/xhtml+xml, */*";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Method = "GET";
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (Stream responsestream = httpResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.UTF8))
{
content = sr.ReadToEnd();
}
}
return content;
}
OK 上面是挪用 我寫的是一個掌握台法式:
static void Main(string[] args)
{
string loginstr = "{要post 的上岸數據包含用戶名和暗碼}";
//從上岸的地址獲得cookie
CookieContainer cookie = GetCookie(loginstr, "http://passport.cnblogs.com/login.aspx");
//這個是進入後台地址
Console.WriteLine(GetContent(cookie, "http://i.cnblogs.com/EditPosts.aspx"));
Console.Read();
}
可以看到我曾經進入了後台了:

假如我是沒有上岸的情形下進入這個地址是如許的:

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。