HttpClient – Cookies – 和JEditorPane

我已成功设法使用httpclient登录到站点并打印出启用该登录的cookie。 但是,我现在卡住了,因为我想使用.setPage(url)函数在JEditorPane中显示后续页面。 但是,当我这样做并使用Wireshark分析我的GET请求时,我发现用户代理不是我的httpclient,而是以下内容:

用户代理:Java / 1.6.0_17

GET请求(在jeditorpane的setPage(URL url)方法中的某处编码)没有使用httpclient检索的cookie。 我的问题是 – 我怎么能以某种方式转移使用httpclient收到的cookie,以便我的JEditorPane可以显示来自网站的URL? 我开始认为这是不可能的,我应该尝试使用普通的Java URL连接等登录,但宁愿坚持使用httpclient,因为它更灵活(我认为)。 据推测,我仍然会遇到cookies问题?

我曾想过扩展JEditorPane类并重写setPage()但我不知道我应该放入的实际代码,因为似乎无法找出setPage()实际上是如何工作的。

任何帮助/建议将不胜感激。

戴夫

正如我在评论中提到的,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内容。 请务必阅读http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JEditorPane.html#getStream(java.net.URL )中的JavaDoc以确保全部捕获角落案件。 我想我的大部分都已整理好了,但我不是专家。

当然,您可以更改代码的HttpClient部分以避免首先将响应加载到内存中,但这是最简洁的方法。 因为你要将它加载到编辑器中,所以它在某些时候都会在内存中。 ;)

在Java 5和6下,有一个默认的cookie管理器,它“自动”支持HttpURLConnection,这是JEditorPane默认使用的连接类型。 基于此博客条目 ,如果你写的东西

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

似乎足以支持JEditorPane中的cookie。 确保在与JEditorPane进行任何互联网通信之前添加此代码。