2009年5月12日 星期二

使用 java http post 取得 google account (AuthSub)

透過輸入 google 帳號 或 google app 的帳號,控制再網頁上的資訊,包含新增、刪除、修改、讀取已有服務的內容
輸入的資訊有兩項,就是帳號和密碼

Sample Request by java


如果想要送的訊息如下
POST /accounts/ClientLogin HTTP/1.0
Content-type: application/x-www-form-urlencoded

accountType=HOSTED_OR_GOOGLE&Email=jondoe@gmail.com&Passwd=north23AZ&service=cl&
source=Gulp-CalGulp-1.05


可以使用以下的java code 去取得


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;


public class ClientLoginDemo {


public static void main(String[] args) throws IOException {


/// Set information
String UesrName="yourgmail@gmail.com"; ///must be set your gmail
String Password="yourcode"; ///must be set your gmail password
String ServiceType="cl"; ///ServiceType see more in http://code.google.com/intl/zh-TW/apis/gdata/faq.html#clientlogin



/// Construct data
String data = "accountType=HOSTED_OR_GOOGLE"+
"&Email="+UesrName+
"&Passwd="+Password+
"&service="+ServiceType+
"&source=Gulp-CalGulp-1.05";



URL url;
try {
url = new URL("https://www.google.com/accounts/ClientLogin");

/// Open Connect
URLConnection conn = url.openConnection();

/// setDoOutput=true than can write message to sent request
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

/// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;

while ((line = rd.readLine()) != null) {
// Process line...
System.out.println(line);

}
wr.close();
rd.close();


} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}

}


ClientLogin Response

成功的話回應如下

HTTP/1.0 200 OK
Server: GFE/1.3
Content-Type: text/plain

SID=DQAAAGgA...7Zg8CTN
LSID=DQAAAGsA...lk8BBbG
Auth=DQAAAGgA...dk3fA5N

上面的ClientLoginDemo 所印出的回應就包含 SID,LSID,Auth 三個回傳值
其中 Auth 的回傳值 可以用這個登入其他的google服務

沒有留言: