我需要以編程方式從Google洞察中下載CSV文件。由於它需要身份驗證,我使用clientLogin來獲取會話ID。通過sessionId獲得對下一個請求的響應
如何通過將會話ID作爲cookie傳遞來下載文件?
我試着使用一個新的URLConnection對象,並在setRequestParameter方法中設置cookie,希望它能驗證我的登錄,然而它似乎並沒有工作。我有一種感覺,我不應該使用兩個單獨的連接,這是真的嗎?
如果是這樣,那麼當我下載文件時如何傳遞會話ID作爲參數?我也嘗試使用相同的連接,這也沒有工作。請幫忙。
try {
URL url1 = new URL("https://www.google.com/accounts/ClientLogin?accountType=GOOGLE&Email=*******.com&Passwd=*****&service=trendspro&source=test-test-v1");
URL url2 = new URL("http://www.google.com/insights/search/overviewReport?cat=0-7&geo=BR&cmpt=geo&content=1&export=1");
URLConnection conn = url1.openConnection();
// fake request coming from browser
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String f = in.readLine();
// obtaining the sid.
String sid=f.substring(4);
System.out.println(sid);
URLConnection conn2 = url2.openConnection();
conn2.setRequestProperty("Cookie", sid);
BufferedInputStream i= new BufferedInputStream(conn2.getInputStream());
FileOutputStream fos = new FileOutputStream("f:/testplans.csv");
BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(i.read(data,0,1024)>=0) {
bout.write(data);
}
bout.close();
in.close();
}
請將您獲得的結果添加到您的控制檯中;例如什麼'System.out.println(sid);'顯示? – foch 2012-02-29 22:55:29