0

我正在使用 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);
4

2 回答 2

0

您不是从 URLConnection 读取内容吗?这样的事情可能会有所帮助。发布您的代码,以便我们获得更多见解。

JTextPane pane;
..
HTMLDocument htmlDocument = (HTMLDocument) pane.getDocument();
htmlDocument.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
htmlDocument.putProperty(Document.StreamDescriptionProperty, pageUrl);
pane.read(connection.getInputStream, htmlDocument);

- 或者 -

您可以尝试使用浏览器 swing 组件而不是 JTextPane。

http://djproject.sourceforge.net/ns/index.html

于 2010-12-06T17:53:53.953 回答
0

Cookie 是与您的浏览器相关的。例如,如果您在 Firefox 中有一些 cookie,Microsoft IE 就看不到这些 cookie。同样,您从您正在寻找的网页获得的 cookie 对您的 Java 应用程序不可用。

而且,JTextPane 不是一个全功能的 HTML 浏览器。您可以使用它来呈现基本的 HTML(实际上是 HTML 2.0,一个更老的 HTML 版本),但它不适用于 cookie、CSS 和其他现在标准的 Web 功能。

您可能想查看功能齐全的 Web 浏览器,例如 Flying Saucer - 请参阅http://weblogs.java.net/blog/2007/07/14/flying-saucer-r7-out

但即使您这样做,飞碟也不会看到您通过其他浏览器获得的 cookie。

于 2010-12-06T17:56:04.857 回答