[英]Sending cookie with HTTP request in Java
我試圖通過創建一系列Http請求來在Java客戶端中獲取某個cookie。 看起來我從服務器上獲取了有效的cookie,但是當我向看似有效的cookie發送到最終URL的請求時,我應該在響應中獲取一些XML行,但是響應為空,因為cookie是錯誤的或無效的,因為會話已關閉或其他無法解決的問題。 服務器分發的cookie在會話結束時到期。
在我看來,該cookie是有效的,因為當我在Firefox中進行相同的調用時,一個具有相同名稱且以3個首字母相同且長度相同的開頭的相似cookie被存儲在firefox中,並且在會議。 然后,如果我僅使用存儲在firefox中的特定cookie來請求最終URL(刪除了所有其他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())
我有點懶得無法調試代碼,但是您可以考慮讓CookieHandler做繁重的工作。 這是我之前做的:
public class MyCookieHandler extends CookieHandler {
private final Map<String, List<String>> cookies =
new HashMap<String, List<String>>();
@Override public Map<String, List<String>> get(URI uri,
Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> ret = new HashMap<String, List<String>>();
synchronized (cookies) {
List<String> store = cookies.get(uri.getHost());
if (store != null) {
store = Collections.unmodifiableList(store);
ret.put("Cookie", store);
}
}
return Collections.unmodifiableMap(ret);
}
@Override public void put(URI uri, Map<String, List<String>> responseHeaders)
throws IOException {
List<String> newCookies = responseHeaders.get("Set-Cookie");
if (newCookies != null) {
synchronized (cookies) {
List<String> store = cookies.get(uri.getHost());
if (store == null) {
store = new ArrayList<String>();
cookies.put(uri.getHost(), store);
}
store.addAll(newCookies);
}
}
}
}
CookieHandler
假定您的cookie處理對於JVM是全局的; 如果您希望按線程進行客戶端會話或進行其他更復雜的事務處理,則最好還是堅持使用手動方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.