2011-12-14 54 views
0

我想寫一點代碼登錄到一個網站。但它不起作用。請你能給我一些建議。這是我的一些代碼:無法使用C#中的httprequest POST登錄網站?

static void Main(string[] args) 
    { 
     CookieContainer container = new CookieContainer(); 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://pagehype.com/login.php"); 
     request.Method = "POST"; 
     request.Timeout = 10000; 
     request.ReadWriteTimeout = 30000; 
     request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) (Prevx 3.0.5)"; 
     request.CookieContainer = container; 

     ASCIIEncoding encoding = new ASCIIEncoding(); 
     string postData = "username=user&password=password&processlogin=1&return="; 
     byte[] data = encoding.GetBytes(postData); 

     request.ContentType = "application/x-www-form-urlencoded"; 
     request.ContentLength = data.Length; 
     Stream newStream = request.GetRequestStream(); 
     newStream.Write(data, 0, data.Length); 
     newStream.Close(); 

     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     StreamReader reader = new StreamReader(response.GetResponseStream()); 
     string htmldoc = reader.ReadToEnd(); 
     response.Close(); 

     Console.Write(htmldoc); 
    } 

非常感謝,

+2

好,你確定是用戶名和密碼的發送方式(即你知道它不是通過HTTP-Authenticate頭髮送的) – neeKo 2011-12-14 10:08:36

+2

你得到的錯誤是什麼? – Maheep 2011-12-14 10:48:03

回答

0

PHP登錄帳號使用PHPSESSID cookie。您需要捕獲並將其傳回CookieContainer中。這是服務器如何將您識別爲已通過身份驗證的用戶。

Cookie在初始響應中的Set-Cookie標頭中設置。你需要分析它重新放到你的貨櫃餅乾(不要忘了路徑(和域?)

var setCookie = response.GetResponseHeader("Set-Cookie"); 
response.Close(); 

container = new CookieContainer(); 
foreach (var cookie in setCookie.Split(',')) 
{ 
    var split = cookie.Split(';'); 
    string name = split[0].Split('=')[0]; 
    string value = split[0].Split('=')[1]; 
    var c = new Cookie(name, value); 

    if (cookie.Contains(" Domain=")) 
     c.Domain = split.Where(x => x.StartsWith(" Domain")).First().Split('=')[1]; 
    else 
    { 
     c.Domain = ".pagehype.com"; 
    } 

    if (cookie.Contains(" Path=")) 
     c.Path = split.Where(x => x.StartsWith(" Path")).First().Split('=')[1]; 

    container.Add(c); 
} 

那麼這個容器添加到您的要求。