這個範例是利用http get 的 request 取得google document 的文件清單的XML
code 如下
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
public class RetrievingListDocumentDemo {
public static void main(String[] args) {
/// Set information
String UesrName="XXXX@gmail.com";
String Password="yourPassword";
String ServiceType="writely"; ///ServiceType see more in http://code.google.com/intl/zh-TW/apis/gdata/faq.html#clientlogin
/// Get Authorization
String Authorization;
Authorization=GetSub(UesrName,Password,ServiceType);
System.out.println("Auth is ");
/// split the message get the code
/// 原始碼= "Auth=................."
/// 將分割為兩段 "Auth="+"...............",取得後面的驗證碼
String[] Authw= Authorization.split("=");
System.out.println(Authw[1]);
URL url;
try {
/// Set url
url = new URL("http://docs.google.com/feeds/documents/private/full");
/// Open Connect
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
/// Set Request method and property
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "GoogleLogin auth="+Authw[1]);
conn.setRequestProperty("GData-Version", "2.0");
/// print sent respond code
/// 列出連線的回應碼如 200 OK
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
/// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
/// Process line...
/// line recode the response XML
System.out.println(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 輸入使用者名稱(email)、密碼以及服務類型
* 取得 Auth 的驗證碼
*
*/
public static String GetSub(String UesrName, String Password, String ServiceType) {
/// Set String record auth
String Authorization="";
try {
/// Construct data
String data = "accountType=HOSTED_OR_GOOGLE"+
"&Email="+UesrName+
"&Passwd="+Password+
"&service="+ServiceType+
"&source=Gulp-CalGulp-1.05";
/// Open Connect
URL url = new URL("https://www.google.com/accounts/ClientLogin");
URLConnection conn = url.openConnection();
/// setDoOutput=true than can write message to sent request
conn.setDoOutput(true);
/// write message to the request
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
/// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
int lineNumber=0;
while ((line = rd.readLine()) != null) {
/// Process line...
lineNumber++;
///System.out.println(line);
/// 第3行才是Auth
if(lineNumber==3)
Authorization=line;
}
wr.close();
rd.close();
} catch (Exception e) {
}
return Authorization;
}
}
沒有留言:
張貼留言