gpt4 book ai didi

java - 如何在 JEditorPane 中设置 html 的超时

转载 作者:行者123 更新时间:2023-12-01 20:26:25 24 4
gpt4 key购买 nike

我正在编写一个RSS阅读器,并使用JEditorpane来显示说明,即html内容。然而,如果一个url失效了,整个程序就会被卡住。我的问题是,是否有办法为其添加超时?或者可能有一些更好的解决方案?

最佳答案

不要使用setPage方法,而是自己创建一个URLConnection,这样你就可以直接设置它的超时属性,然后将连接的InputStream传递给JEditorPane的read方法:

URL url = new URL("http://example.com");

// Five seconds
long timeout = 5000;

URLConnection connection = url.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);

editorPane.setContentType("text/html");
try (InputStream stream = connection.getInputStream()) {
editorPane.read(stream, editorPane.getDocument());
}

除了……

如果 JEditorPane 从 InputStream 加载 HTML 只是为了发现 header 或元元素声明了不同的字符集,则 JEditorPane 需要重新开始。它通过抛出 ChangedCharSetException 来表明这种需要。 .

此时,需要创建一个 HTMLDocument,设置其 "IgnoreCharsetDirective" 属性,并使用新发现的字符集创建一个 Reader 并将 URL 直接从该 Reader 加载到文档中.

所以,修改后的版本如下所示:

URL url = new URL("http://example.com");

// Five seconds
int timeout = 5000;

URLConnection connection = url.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);

editorPane.setContentType("text/html");
try (InputStream stream = connection.getInputStream()) {
editorPane.read(stream, editorPane.getDocument());
} catch (ChangedCharSetException e) {
String newContentType = e.getCharSetSpec();
editorPane.setContentType(newContentType);

EditorKit editorKit = editorPane.getEditorKit();
Document doc = editorKit.createDefaultDocument();
doc.putProperty("IgnoreCharsetDirective", true);
editorPane.setDocument(doc);

String charset;
try {
charset = new DataFlavor(newContentType).getParameter("charset");
} catch (ClassNotFoundException ce) {
throw new IOException(ce);
}

connection = url.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);

try (Reader reader =
new InputStreamReader(connection.getInputStream(), charset)) {

editorKit.read(reader, doc, 0);
} catch (BadLocationException le) {
throw new IOException(le);
}
}

关于java - 如何在 JEditorPane 中设置 html 的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com