我想通過創建一系列Http請求來獲取java客戶端中的某個cookie。 它看起來像我從服務器得到一個有效的cookie,但當我發送一個請求到最終的URL與看似有效的cookie時,我應該在響應中獲得一些XML的行,但響應是空白的,因爲cookie是錯誤的或因爲會話已關閉或其他問題而無效,這是我無法弄清楚的。 服務器發出的cookie在會話結束時到期。在Java中使用HTTP請求發送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())
有沒有想過只是切換到普通的http客戶端? http://hc.apache.org/httpclient-3.x/ – leonm 2010-03-27 10:49:44
看起來你正在手動完成這一切。我不知道你如何管理會話過期。如果你把所有的服務器代碼放在一個servlet中,它會容易得多。這是一個選項嗎? – John 2010-03-27 10:56:55