0

我已经测试了第一步(登录页面)并且它有效。我输入了所有参数(用户、密码等),然后可以打印结果(包含我的数据的页面)。问题是当我尝试从该网站下载文件时。我需要第一步的饼干。在我下载的文件中,我有消息:“会话过期”。这是我的代码:

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();  

提前致谢。

4

1 回答 1

0

您是否尝试在关闭连接之前检查第一页上的 cookie 标题?我会尝试类似的东西:

String cookies = conn.getHeaderField("Set-Cookie");

然后在以下连接中设置 cookie,在执行 connect() 之前,使用:

connDownload.setRequestProperty("Cookie", cookies);

...看看这是否有效...

于 2013-10-24T04:17:30.830 回答