2011-04-26 81 views
1

我已成功地使用httpclient登錄到網站並打印出啓用該登錄的cookie。 但是,我現在卡住了,因爲我想使用.setPage(url)函數在JEditorPane中顯示後續頁面。然而,當我做到這一點,使用Wireshark的分析我的GET請求,我看到的是,用戶代理是不是我的HttpClient但以下幾點:HttpClient - Cookie和JEditorPane

的User-Agent:的Java/1.6.0_17

的GET請求(這是編碼在jeditorpane的setPage(URL url)方法的某處)沒有使用httpclient檢索到的cookie。我的問題是 - 我怎樣才能以某種方式傳輸用httpclient接收的cookie,以便我的JEditorPane可以顯示來自站點的URL? 我開始認爲這是不可能的,我應該嘗試使用普通的Java URLconnection等登錄,但寧願堅持httpclient,因爲它更靈活(我認爲)。據推測,我仍然有一個問題,餅乾?

我曾想過擴展JEditorPane類並覆蓋setPage(),但我不知道實際的代碼,我應該把它放在它似乎無法找到如何setPage()實際工作。

任何幫助/建議將不勝感激。

戴夫

+1

您在這裏遇到的問題是,當您調用setPage()時,HttpClient和JVM用於獲取URL的底層實現是完全不同的動物。因此,cookies不會神奇地結轉。 – stevevls 2011-04-26 16:04:18

+0

@stevevls,我認爲這可能是這種情況。所以如果我使用Urlconnection路線,他們會自動繼續嗎?感謝您的幫助 – user725687 2011-04-26 16:20:49

+0

所以我想我已經想出瞭如何去做你想做的事情。看看答案,如果它適合你,請接受它。祝你好運! – stevevls 2011-04-26 18:33:02

回答

0

正如我在評論,HttpClient的和使用的JEditorPane中獲取URL內容不說話彼此的URLConnection提及。所以,HttpClient可能提取的任何cookie都不會轉移到URLConnection。但是,你也可以繼承的JEditorPane像這樣:

final HttpClient httpClient = new DefaultHttpClient(); 

/* initialize httpClient and fetch your login page to get the cookies */ 

JEditorPane myPane = new JEditorPane() { 
    protected InputStream getStream(URL url) throws IOException { 

     HttpGet httpget = new HttpGet(url.toExternalForm()); 

     HttpResponse response = httpClient.execute(httpget); 
     HttpEntity entity = response.getEntity(); 

     // important! by overriding getStream you're responsible for setting content type! 
     setContentType(entity.getContentType().getValue()); 

     // another thing that you're now responsible for... this will be used to resolve 
     // the images and other relative references. also beware whether it needs to be a url or string 
     getDocument().putProperty(Document.StreamDescriptionProperty, url); 

     // using commons-io here to take care of some of the more annoying aspects of InputStream 
     InputStream content = entity.getContent(); 
     try { 
      return new ByteArrayInputStream(IOUtils.toByteArray(content)); 
     } 
     catch(RuntimeException e) { 
      httpget.abort(); // per example in HttpClient, abort needs to be called on unexpected exceptions 
      throw e; 
     } 
     finally { 
      IOUtils.closeQuietly(content); 
     } 
    } 
}; 

// now you can do this! 
myPane.setPage(new URL("http://www.google.com/")); 

這樣調整,你將使用HttpClient的獲取你的JEditorPane中的URL內容。請務必閱讀JavaDoc http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JEditorPane.html#getStream(java.net.URL)以確保您抓住所有的角落案例。我想我已經把他們中的大多數排序了,但我不是專家。

當然,您可以更改代碼的HttpClient部分,以避免首先將響應加載到內存中,但這是最簡潔的方式。而且,由於您將要將其加載到編輯器中,因此在某個時刻它將全部存儲在內存中。 ;)

0

根據Java 5 & 6,有一個默認的cookie管理器「自動」支持HttpURLConnection,JEditorPane默認使用的連接類型。基於this blog entry ,如果你喜歡寫東西

CookieManager manager = new CookieManager(); 
manager.setCookiePolicy(CookiePolicy.ACCEPT_NONE); 
CookieHandler.setDefault(manager); 

似乎不足以支持cookies在JEditorPane中。 請確保在與JEditorPane進行任何Internet通信之前添加此代碼。