2012-10-21 111 views
0

我已经测试了第一步(登录页面),它的工作原理。我把所有参数(用户,通过等),我可以打印结果(页面与我的数据)。问题是当我尝试从该网站下载文件时。我需要第一步的cookies。在我下载的文件中,我有消息:“过期的会话”。这是我的代码:使用发布请求从页面下载文件(需要cookies)

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

看看Apache HttpClient - http://hc.apache.org/httpcomponents-client-ga – GreyBeardedGeek

回答

0

在关闭连接之前,您是否尝试在第一页上检查cookie的标头?我想尝试这样的:

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

随后设置cookie在下面的连接,连接执行()之前,使用:

connDownload.setRequestProperty("Cookie", cookies);

...看看是否能工程...

相关问题