获取URL内容有时包含奇怪的值

时间:2019-07-12 16:24:43

标签: java

我已经使用此函数以字符串形式获取URL的内容:

static String getUrlContent(String site) {
    String text = "";
    try {
        URL url = new URL(site);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.addRequestProperty("user-agent", "Mozilla/5.0 (Widows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
        InputStream in = new BufferedInputStream(con.getInputStream());
        while(true) {
            byte[] s = new byte[1000];
            if(in.read(s) == -1) break;
            text += new String(s);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }
    return text;
}

有时,此字符串包含大范围的奇怪字符,Eclipse仅将这些字符显示为正方形。如果我再次使用相同的URL调用它们,它们将消失(或出现在其他位置)。为什么会这样,我该如何避免呢?

0 个答案:

没有答案