所以 Google 提供了一種 ClientLogin 方式的驗證, 讓使用者只要取得一次驗證碼, 之後就不必一直作驗證的動作
以下 是官方的 說明網站
java 範例之前寫過了 見 使用 java http post 取得 google account (AuthSub)
這裡就說明 C# 的方法
輸入 帳號、 密碼即可
會得到 strResponse 如圖, 但我們只要 auth 的驗證碼就好
所以在此用 Split('=') 的方法找出 需要的字串
/**
* @name GetGoogleAuth
*
* Get Google Auth code
* @return string Auth
*/
public string GetGoogleAuth(string Account, string Password)
{
string Auth="";
try
{
/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin");
/// Set proxy
SetProxyServer(req);
/// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string strNewValue = "accountType=HOSTED_OR_GOOGLE&Email=" + Account +
"&Passwd=" + Password +
"&service=cl&source=Gulp-CalGulp-1.05";
req.ContentLength = strNewValue.Length;
/// Write the request
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();
/// Do the request to get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
/// Split string and set token
string[] parts = strResponse.Split('=');
/// Save the Auth Token
/// Auth Token id in the last string
GoogleAuthToken= parts[parts.Length - 1];
stIn.Close();
Auth = GoogleAuthToken;
}
catch
{
Auth = "";
}
return Auth;
}
/**
* @name SetProxyServer
*
* Set the Proxy Server if have Proxy Server
*
*/
public void SetProxyServer(HttpWebRequest req)
{
IWebProxy iProxy = WebRequest.DefaultWebProxy;
/// potentially, setup credentials on the proxy here
iProxy.Credentials = CredentialCache.DefaultCredentials;
req.Proxy = iProxy;
}
沒有留言:
張貼留言