我正在使用 JTextPane 显示来自不属于我的网页的数据,因此我无法控制其内容。它需要用户登录,因此我使用 URLConnections 连接到该网页并使用 URLConnection 中的 cookie 来检索数据。这很好用。但是,当我将此数据放在内容类型设置为 text/html 的 JTextPane 中时,图像不会显示,因为它们需要发送具有会话 ID 和内容的 cookie 才能检索上传的图像。
有什么方法可以让 JTextPane(尽管我可以在 jdk 中使用任何其他显示 html 的东西)使用我的 cookie?
谢谢。
我将 cookie 存储在链表中:
loadText = "Logging in...";
url = new URL("http://www.example.com/login.php");
connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("username=" + URLEncoder.encode(username, "UTF-8")
+ "&password=" + URLEncoder.encode(password, "UTF-8")
+ "&testcookies=1");
out.flush();
out.close();
List<String> cookies = new LinkedList<String>();
for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = connection.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
cookies.add(cookie);
}
}
而且我还需要去除不必要的 HTML,这给了我一个插入文本窗格的字符串:
String p1 = rawPage.split("<div id=\"contentstart\">")[1]
.split("</div><!--id='contentstart'-->")[0];
p1 = p1.replaceAll("<p><strong></strong></p>", "");
p1 = p1.replaceAll("<p></p>", "");
parsed = true;
JTextPane tp = new JTextPane();
tp.setEditable(false);
JScrollPane js = new JScrollPane();
js.getViewport().add(tp);
js.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(js);
js.setSize(640, 480);
tp.setContentType("text/html");
tp.setText(p1);