我使用 POST 方法(来自 apache 的 httpclient)登录网站。
我让 HttpClient 执行 HttpPost,让连接管理器释放它,然后我想发布一条 GET 消息,打开一个 php-URL 文件以下载 pdf。
但我得到的只是“ session 已过期”页面的 html 文件
(println: 文件: index_GT_neu.html?fehlermeldung=fehler_sessioncheck
)
我在想,一旦我使用 HttpClient 的实例登录该站点,我就可以打开另一个只有在登录后才可用的 URL。但显然我错了。 有人可以给我提示吗? 提前致谢!
这是我的 main 的样子:
// prepare post method
HttpPost post = new HttpPost("http://epaper02.niedersachsen.com/epaper/index_GT_neu.html");
//prepare get method
HttpGet httpget = new HttpGet("http://epaper01.niedersachsen.com/epaper/getfile.php?pdf=0114_GTB_HP_01.pdf&zeitung=GT&ekZeitung=&Y=11&M=01&D=14&C=0");
// add parameters to the post method
List <NameValuePair> parameters = new ArrayList <NameValuePair>();
parameters.add(new BasicNameValuePair("username", "test"));
parameters.add(new BasicNameValuePair("passwort", "test"));
UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
post.setEntity(sendentity);
// create the client and execute the post method
HttpClient client = new DefaultHttpClient();
HttpResponse postResponse = client.execute(post);
//Output the Response from the POST
System.out.print(convertInputStreamToString(postResponse.getEntity().getContent()));
//releasing POST
EntityUtils.consume(postResponse.getEntity());
//Execute get
HttpContext context = new BasicHttpContext();
HttpResponse getResponse = client.execute(httpget, context);
System.out.println("Statusline: " + getResponse.getStatusLine());
if (getResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw new IOException(getResponse.getStatusLine().toString());
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
String currentUrl = URLDecoder.decode(currentReq.getURI().toString(), "UTF-8");
int i = currentUrl.lastIndexOf('/');
String fileName = null;
if (i < 0) {
fileName = currentUrl;
} else {
fileName = currentUrl.substring(i + 1);
}
System.out.println("File: " + fileName);
//Create file
OutputStream os = new FileOutputStream( fileName);
InputStream is = getResponse.getEntity().getContent();
byte[] buf = new byte[4096];
int read;
while ((read = is.read(buf)) != -1) {
os.write(buf, 0, read);
}
os.close();
client.getConnectionManager().shutdown();
最佳答案
默认情况下,DefaultHttpClient
没有 cookie 存储。需要一个 cookie 存储来存储最初填充的 cookie 或在与 HTTP 客户端交互时获得的 cookie。一旦深入研究这个主题,您就会开始考虑 cookie 的范围/共享。
您可以使用额外的一行代码启用 cookie 存储:
DefaultHttpClient client = new DefaultHttpClient();
client.setCookieStore(new BasicCookieStore());
我知道,这可能有点晚了,仍然是 HTH。
关于Java httpclient 登录网站并下载文件 - session 问题!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4701284/