First, we define some variables:
C # code
Private const string NET_SESSIONID = "ASP. NET_SessionId = "; private const string CLIENTKEY =" ClientKey = "; string aspcookie =" "; private string html =" "; private string sessionId = ""; private string clientKey = ""; private string viewState = "";
1. Use HttpWebRequest to obtain CSDN logon information, such as ASP. NET_SessionId, ClientKey, and _ VIEWSTATE. This step can be placed in Login_Load. The following code is used:
C # code
Private void Login_Load (object sender,
EventArgs e ){
HttpWebRequest request = WebRequest. Create ("http://passport.csdn.net/UserLogin.aspx") as HttpWebRequest;
Request. Credentials = CredentialCache. DefaultCredentials;
Request. Accept = "*/*";
Request. Referer = "http://passport.csdn.net/UserLogin.aspx ";
Request. UserAgent = "Mozilla/4.0 (compatible;
MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2;
. Net clr 2.0.50727;. net clr 3.5.30729;
. Net clr 3.0.30729;. NET4.0C;. NET4.0E )";
Request. Method = "GET ";
Request. KeepAlive = true;
Request. Headers. Set ("Accept-Language", "zh-CN ");
Request. Headers. Set ("Accept-Encoding", "gzip, deflate ");
HttpWebResponse response = request. GetResponse () as HttpWebResponse;
System. IO. Stream responseStream = response. GetResponseStream ();
System. IO. StreamReader reader = new System. IO. StreamReader (responseStream, Encoding. GetEncoding ("UTF-8 "));
Html = reader. ReadToEnd ();
String viewStateFlag = "id = \" _ VIEWSTATE \ "value = \"";
Int I = html. IndexOf (viewStateFlag) + viewStateFlag. Length;
Int j = html. IndexOf ("\" ", I );
ViewState = html. Substring (I, j-I );
Aspcookie = response. Headers. Get ("Set-Cookie ");
SessionId = GetSessionId ();
ClientKey = GetClientKey ();
// Obtain the image Verification Code
GetCode () ;}/// <summary> /// obtain the ClientKey /// </summary> ///
<Returns> </returns> private string GetClientKey (){
// This is only used to obtain the length of the ClientKey value string id = "bb32434c-3bb3-4e44-92c3-8952f631ca87 ";
Int index = aspcookie. IndexOf (CLIENTKEY) + CLIENTKEY. Length;
String str = aspcookie. Substring (index, id. Length );
Return str;} // <summary> // obtain ASP. NET_SessionId = // </summary> // <returns> </returns> private string GetSessionId (){
String id = "5mhl0tvbw5shlpnhxgwnck45 ";
Int index = aspcookie. IndexOf (NET_SESSIONID) + NET_SESSIONID.Length;
String str = aspcookie. Substring (index, id. Length); return str ;}