我试图通过创建一系列Http请求在
Java客户端中获取某个cookie.
看起来我从服务器获得了一个有效的cookie,但是当我用一个看似有效的cookie向fnal url发送请求时,我应该在响应中获得一些XML行,但响应是空白的,因为cookie是错误或因会话已关闭或其他我无法弄清楚的问题而无效.
服务器发出的cookie在会话结束时到期.
在我看来,cookie是有效的,因为当我在Firefox中执行相同的调用时,类似的cookie具有相同的名称,并以3个相同的字母和相同的长度开始存储在firefox中,也会在到期结束时到期会话.
如果我然后向最终URL发出请求,只有这个特定的cookie存储在firefox中(删除了所有其他cookie),那么xml很好地呈现在页面上.
关于我在这段代码中做错了什么的任何想法?
另一件事是,当我在这段代码中使用生成并存储在Firefox中的非常相似的cookie中的值时,最后一个请求会在HTTP响应中提供XML反馈.
// Validate
url = new URL(URL_VALIDATE);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.connect();
String headerName = null;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
if (conn.getHeaderField(i).startsWith("JSESSIONID")) {
cookie = conn.getHeaderField(i).substring(0, conn.getHeaderField(i).indexOf(";")).trim();
}
}
}
// Get the XML
url = new URL(URL_XML_TOTALS);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.connect();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
reader.close();
//Output the response
System.out.println(answer.toString())