【问题标题】:Download a file from a page (cookies needed) using post request使用 post 请求从页面下载文件(需要 cookie)
【发布时间】:2012-10-11 18:08:17
【问题描述】:

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

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

提前致谢。

【问题讨论】:

标签: java cookies httpurlconnection


【解决方案1】:

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

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

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

connDownload.setRequestProperty("Cookie", cookies);

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

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多