我已经测试了第一步(登录页面)并且它有效。我把所有参数(用户,传递等),我可以打印结果(页面与我的数据)。问题是当我尝试从该网络下载文件时。我需要第一步的cookie。在我下载的文件中,我收到了消息:“Expired session”。这是我的代码:
URL login = new URL("...");
URL download_page = new URL("...");
URL document_link new URL("...");
//String for request
String data_post = "username=name&password=1234&other_data=...";
//Login page
HttpURLConnection conn = (HttpURLConnection)login.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_post);
wr.close();
conn.connect();
//Download page
HttpURLConnection connDownload = (HttpURLConnection)download_page.openConnection();
connDownload.connect();
//Link to the file
HttpURLConnection connFile = (HttpURLConnection)document_link.openConnection();
connFile.connect();
BufferedInputStream in = new BufferedInputStream(connFile.getInputStream());
File saveFile = new File("myfile.txt");
OutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
byte[] buf = new byte[256];
int n = 0;
while ((n=in.read(buf))>=0) {
out.write(buf, 0, n);
}
out.flush();
out.close();
提前致谢。
答案 0 :(得分:0)
在关闭连接之前,您是否尝试在第一页上检查Cookie的标头?我会尝试类似的事情:
String cookies = conn.getHeaderField("Set-Cookie");
然后在执行connect()之前,在以下连接中设置cookie,使用:
connDownload.setRequestProperty("Cookie", cookies);
......看看是否有效......