4)如果登錄成功,返回頁面中retcode值為0;get方式訪問網頁中l(wèi)ocation.replace處的地址。
保存這三次訪問頁面的cookie后下次再訪問新浪微博用不再需要重新登錄了。具體代碼如下:
static CookieContainer cc = new CookieContainer();
public static int SinaLogin(string uid,string psw, CookieContainer cc)
{
string uidbase64 = Base64Code(uid); //處理登錄賬戶如***@**.com
string url = " + uidbase64 + "&client=ssologin.js(v1.3.16)";
HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create(newUri(url)); //獲取servertime和 nonce
webRequest1.CookieContainer = cc;
HttpWebResponse response1 =(HttpWebResponse)webRequest1.GetResponse();
StreamReader sr1 = new StreamReader(response1.GetResponseStream(),Encoding.UTF8);
string res = sr1.ReadToEnd();
int start = res.IndexOf("servertime");
if (start < 0 || start >= res.Count()) return -1;
int end = res.IndexOf(',', start);
if (end < 0 || end >= res.Count()) return -1;
string servertime = res.Substring(start + 12, end - start -12);
start = res.IndexOf("nonce");
if (start < 0 || start >= res.Count()) return -1;
end = res.IndexOf(',', start);
if (end < 0 || end >= res.Count()) return -1;
string nonce = res.Substring(start + 8, end - start - 9);
string password = hex_sha1("" + hex_sha1(hex_sha1(psw)) +servertime + nonce); //處理新浪微博用戶密碼psw
string str ="entry=weibo&gateway=1&from=&savestate=7&useticket=1&ssosimplelogin=1&su="+
uidbase64 + "&service=miniblog&servertime=" + servertime +"&nonce=" + nonce + "&pwencode=wsse&sp=" + password +"&encoding=utf-8&url=" +
HttpUtility.UrlEncode(" byte[] bytes;
ASCIIEncoding encoding = new ASCIIEncoding();
bytes = encoding.GetBytes(str);
// bytes =System.Text.Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(str));
HttpWebRequest webRequest2 =(HttpWebRequest)WebRequest.Create(" webRequest2.Method = "POST";
webRequest2.ContentType = "application/x-www-form-urlencoded";
webRequest2.ContentLength = bytes.Length;
webRequest2.CookieContainer = cc;
Stream stream;
stream = webRequest2.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
HttpWebResponse response2 =(HttpWebResponse)webRequest2.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(),Encoding.Default);
string res2 = sr2.ReadToEnd();
int pos = res2.IndexOf("retcode");
if (pos < 0 || pos > res2.Count()) return -1;
int retcode = -1;
for (pos += 8; pos < 100 + res2.Count(); pos++)
{
if (res2[pos] < '0' || res2[pos] > '9')
{
retcode = 0;
break;
}
else if (res2[pos] > '0' && res2[pos] <= '9')
break;