本文目录导读:

这个错误信息表明在使用 JEditorPane 和 HTMLEditorKit 解析 HTML 内容时,遇到了一个格式错误的 URL,这通常发生在以下几种情况:
常见原因
- HTML 中包含无效的 URL(如缺少协议、特殊字符未转义)
- 相对路径解析失败(当没有设置基础 URL 时)
- URL 中包含非法字符(如空格、中文等未编码)
- 协议不受支持(如
ftp://但环境不支持)
解决方案
设置基础 URL
JEditorPane editor = new JEditorPane();
editor.setEditorKit(new HTMLEditorKit());
// 设置基础 URL 以解析相对路径
try {
editor.setPage(new URL("http://example.com/base/"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
// 设置 HTML 内容
editor.setText("<img src='images/photo.jpg'>"); // 相对路径
编码特殊字符
// 对 URL 中的特殊字符进行编码 String url = "http://example.com/file with spaces.jpg"; String encodedUrl = URLEncoder.encode(url, "UTF-8"); // 注意:URLEncoder 会编码整个字符串,包括 ://,所以需要分别处理
更好的方法:
URI uri = new URI("http", "example.com", "/path/file with spaces.jpg", null);
String cleanUrl = uri.toASCIIString();
使用自定义解析器
HTMLEditorKit kit = new HTMLEditorKit() {
@Override
public Document createDefaultDocument() {
HTMLDocument doc = new HTMLDocument() {
@Override
public HTMLEditorKit.ParserCallback getReader(int pos) {
return new HTMLEditorKit.ParserCallback() {
@Override
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
// 拦截标签处理,修复 URL
if (t == HTML.Tag.IMG || t == HTML.Tag.A) {
String src = (String) a.getAttribute(HTML.Attribute.SRC);
if (src != null && !src.startsWith("http")) {
// 尝试修复相对路径
src = "file:///" + new File(src).getAbsolutePath();
a.removeAttribute(HTML.Attribute.SRC);
a.addAttribute(HTML.Attribute.SRC, src);
}
}
super.handleSimpleTag(t, a, pos);
}
};
}
};
return doc;
}
};
editor.setEditorKit(kit);
捕获并忽略错误
try {
editor.setText(htmlContent);
} catch (Exception e) {
System.err.println("HTML 解析警告(已忽略): " + e.getMessage());
// 可以尝试移除问题标签后重试
}
预处理 HTML 内容
public String sanitizeHtmlUrls(String html) {
// 修复常见的 URL 问题
html = html.replaceAll("href=\"(?!http|ftp|mailto)", "href=\"http://");
html = html.replaceAll("src=\"(?!http|ftp|data:)", "src=\"http://");
return html;
}
调试建议
-
记录问题 URL:
System.setProperty("sun.net.http.errorstream.enableBuffering", "true"); editor.addPropertyChangeListener("page", evt -> { if (evt.getNewValue() == null) { System.err.println("页面加载失败"); } }); -
手动检查 HTML 内容:
String content = editor.getText(); System.out.println("HTML 内容长度: " + content.length()); // 检查前 500 个字符中的 URL int urlStart = content.indexOf("http"); if (urlStart >= 0) { String urlSection = content.substring(urlStart, Math.min(urlStart + 200, content.length())); System.out.println("找到 URL: " + urlSection); }
完整示例
import javax.swing.*;
import javax.swing.text.html.*;
import java.io.IOException;
import java.net.*;
public class FixedHtmlViewer {
public static void main(String[] args) {
JFrame frame = new JFrame();
JEditorPane editor = new JEditorPane();
editor.setEditable(false);
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
editor.setEditorKit(kit);
editor.setDocument(doc);
// 设置基础 URL
try {
doc.setBase(new URL("http://localhost/"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
String html = "<html><body>"
+ "<a href='../relative/path'>链接</a>"
+ "<img src='file with spaces.jpg'>"
+ "</body></html>";
// 预处理
html = html.replace("file with spaces.jpg",
URLEncoder.encode("file with spaces.jpg", java.nio.charset.StandardCharsets.UTF_8));
editor.setText(html);
frame.add(new JScrollPane(editor));
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
如果问题依然存在,请提供具体的 HTML 内容和相关的 Java 代码片段,这样可以给出更精准的解决方案。