HttpClient-Cookies-和JEditorPane

HttpClient-Cookies-和JEditorPane,第1张

HttpClient-Cookies-和JEditorPane

正如我在评论中提到的那样,HttpClient和JEditorPane用于获取URL内容的URLConnection彼此不对话。因此,HttpClient可能已获取的任何cookie都不会转移到URLConnection。但是,您可以像这样子类化JEditorPane:

final HttpClient httpClient = new DefaultHttpClient();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
,以确保您捕获了所有JavaDoc 角落里的情况。我想我已经对它们中的大多数进行了排序,但是我不是专家。

当然,您可以在代码的HttpClient部分周围进行更改,以避免首先将响应加载到内存中,但这是最简洁的方法。而且由于您要将其加载到编辑器中,因此某个时刻它们都将保存在内存中。;)



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5499911.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存