Java-从url读取页面源返回未知字符

时间:2019-02-04 15:02:40

标签: java amazon-web-services aws-lambda amazon-dynamodb amazon

我正在使用下面的代码从NetBeans中具有“ UTF-8”字符集的URL(https://www.amazon.com)中读取页面源,但是它返回未知字符(随附的图像)。我不知道这是什么问题,如果能帮助我修改代码以使其正常工作,我将不胜感激。谢谢。

enter image description here

public static String getURLSource(String url) throws IOException
{
    URL urlObject = new URL(url);
    URLConnection urlConnection = urlObject.openConnection();
    urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

    return toString(urlConnection.getInputStream());
}

private static String toString(InputStream inputStream) throws IOException
{
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
    {
        String inputLine;
        StringBuilder stringBuilder = new StringBuilder();
        while ((inputLine = bufferedReader.readLine()) != null)
        {
            stringBuilder.append(inputLine);
        }

        return stringBuilder.toString();
    }
}

1 个答案:

答案 0 :(得分:0)

使用HttpsUrlConnection代替UrlConnection。参见a similar question