我需要用程序从Google insights下载一个CSV文件。由于它需要身份验证,我使用clientLogin来获取会话id。
如何通过将会话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();
}
尝试以下操作:链接。检查最重要的答案:他们不使用SID,而是使用Auth。
如果它适用于谷歌阅读器,它可能也适用于谷歌洞察。