2011-04-26 84 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通信之前添加此代码。