2012-12-31 28 views
2

我目前使用下面的一段代碼,即可獲得該網站的cookie:有沒有辦法使用WebClient從受密碼保護的位置而不是Httprequest獲取登錄cookie?

 bool IsLoginSuccessful = false; 
    try 
    { 
    //Get Token and Authorization URL 
    HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("https://updates.site.com/download"); 
    wr.AllowAutoRedirect = true; 
    WebResponse response = wr.GetResponse(); 
    response.Close(); 
    string data = response.ResponseUri.OriginalString; 
    string ssoToken = data.Split('=')[1]; 
    string authData = String.Format("ssousername={0}&password={1}&site2pstoretoken={2}", username, password, ssoToken); 
    string ssoServer = response.ResponseUri.Scheme + "://" + response.ResponseUri.Host; 
    string ssoAuthUrl = "sso/auth"; 

    // now let's get our cookie for the download 
    byte[] dataBytes = Encoding.UTF8.GetBytes(authData); 
    string url = ssoServer + "/" + ssoAuthUrl; 
    wr = (HttpWebRequest)HttpWebRequest.Create(url); 

    //MyCookies is a CookieContainer I use to store the login cookies 
    wr.CookieContainer = MyCookies; 
    wr.Method = "POST"; 
    wr.ContentLength = dataBytes.Length; 
    wr.ContentType = "application/x-www-form-urlencoded"; 
    Stream dataStream = wr.GetRequestStream(); 
    dataStream.Write(dataBytes, 0, dataBytes.Length); 
    dataStream.Close(); 
    response = wr.GetResponse(); 
    response.Close(); 

    if (wr.CookieContainer.Count > 0) 
    { 
     IsLoginSuccessful = true; 
    } 
    } 

我不知道是否有使用Web客戶端或者從它繼承的類的方式,來獲得餅乾代替使用HttpRequest?

+1

看看[這個問題](http://stackoverflow.com/questions/1777221/using-cookiecontainer-with-webclient-class )。這應該會給你足夠的信息來幫助你一路走來。 –

回答

1

獲取cookie而不是使用HttpRequest?

Cookies是HttpRequest的屬性:

int loop1, loop2; 
HttpCookieCollection MyCookieColl; 
HttpCookie MyCookie; 

MyCookieColl = Request.Cookies; 

// Capture all cookie names into a string array. 
String[] arr1 = MyCookieColl.AllKeys; 

// Grab individual cookie objects by cookie name. 
for (loop1 = 0; loop1 < arr1.Length; loop1++) 
{ 
    MyCookie = MyCookieColl[arr1[loop1]]; 
    Response.Write("Cookie: " + MyCookie.Name + "<br>"); 
    Response.Write ("Secure:" + MyCookie.Secure + "<br>"); 

    //Grab all values for single cookie into an object array. 
    String[] arr2 = MyCookie.Values.AllKeys; 

    //Loop through cookie Value collection and print all values. 
    for (loop2 = 0; loop2 < arr2.Length; loop2++) 
    { 
     Response.Write("Value" + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>"); 
    } 
} 
相關問題