I am trying to get a specific cookie in a java client by creating a series of Http requests. It looks like I am getting a valid cookie from the server, but when I send a request to the fnal url with a seemingly valid cookie, I should get some XML strings in the response, but the answer is empty because the cookie is incorrect or invalidated because the session is closed or another problem that I cannot understand. The cookie issued by the server expires at the end of the session.
It seems to me that the cookie is valid, because when I make the same calls in Firefox, a similar cookie with the same name and starting with the first 3 identical letters and the same length is saved in firefox, also ends at the end of the session. If I then make a request to the final URL with just this particular cookie stored in firefox (all other cookies are deleted), the xml displays nicely on the page.
Any ideas on what I'm doing wrong in this part of the code? One more thing, when I use the value from a very similar cookie generated and stored in Firefox in this code snippet, the last request gives an XML response in the HTTP response.
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();
}
}
}
url = new URL(URL_XML_TOTALS);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.connect();
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
reader.close();
System.out.println(answer.toString())
source
share