2010-03-27 207 views
4

我想通過創建一系列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()) 
+1

有沒有想過只是切換到普通的http客戶端? http://hc.apache.org/httpclient-3.x/ – leonm 2010-03-27 10:49:44

+1

看起來你正在手動完成這一切。我不知道你如何管理會話過期。如果你把所有的服務器代碼放在一個servlet中,它會容易得多。這是一個選項嗎? – John 2010-03-27 10:56:55

回答

5

我感覺有點懶得調試代碼,但你可能會考慮讓一個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;如果你想要每個線程的客戶端會話或其他一些更復雜的事務處理,你最好堅持使用手動方法。