【问题标题】:How to get source code from given URL in correct character encoding in java? [duplicate]java - 如何在Java中以正确的字符编码从给定的URL获取源代码? [复制]
【发布时间】:2014-07-02 23:05:47
【问题描述】:

我有一个代表 url 的字符串,我需要获取它的 HTML 源代码。 问题是,我找不到正确编码的方法(诸如 à è ì ò ù 之类的字母没有被正确读取,只是作为“??”接收)。

最好的方法是什么?我遇到了很多解决方案,但显然没有一个有效。

这是我的代码

private String getHtml(String url, String idSession) throws IOException 
{
    URL urlToCall   = null;
    String html     = "";

    try 
    {
        urlToCall = new URL(url); 
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        return "";
    }

    HttpURLConnection conn;

        conn = (HttpURLConnection) urlToCall.openConnection();
        conn.setRequestProperty("cookie", "JSESSIONID=" + idSession);
        conn.setDoOutput(false);
        conn.setReadTimeout(200*1000);
        conn.setConnectTimeout(200*1000);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        InputStream openStream = conn.getInputStream();
        byte[] buffer = new byte[ 1024 ];
        int size = 0;
        while( (size = openStream.read( buffer ) ) != -1 ) {
            output.write( buffer, 0, size );
        }
    html = output.toString("utf-8");
    return html;

}

【问题讨论】:

  • 我补充说显然它不适用于 linux。

标签: java html encoding


【解决方案1】:

试试 JSOUP

    String url = "http://www.hamzaalayed.com/";
Document document = Jsoup.parse(new URL(url).openStream(), "utf-8", url);
Element paragraph = document.select("p").first();

for (Node node : paragraph.childNodes()) {
    if (node instanceof TextNode) {
        System.out.println(((TextNode) node).text().trim());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多