从InputStreamReader中提取文本不能在UTF-8

时间:2018-04-21 21:21:35

标签: java utf-8 inputstreamreader

我试图阅读以下API文本页面:

  

https://api.stackexchange.com/2.2/users?page=1&pagesize=9&fromdate=1221436800&todate=1523318400&order=desc&min=1&max=2000000&sort=reputation&site=stackoverflow

使用InputStreamReader,我想提取文本并逐行打印。

问题是文本的格式不被识别为UTF-8。所以输出看起来像丑陋的: ????

该方法的代码如下:

String testURL = "https://api.stackexchange.com/2.2/users?page=1&pagesize=9&fromdate=1221436800&todate=1523318400&order=desc&min=1&max=2000000&sort=reputation&site=stackoverflow";

            URL url = null;
            try
            {
                url = new URL(testURL);
            } catch (MalformedURLException e1)
            {
                e1.printStackTrace();
            }

            InputStream is = null;

            try
            {
                is = url.openStream();
            } catch (IOException e1)
            {
                e1.printStackTrace();
            }


            try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")))
            {
                String line;

                while ((line = br.readLine()) != null)
                {
                    System.out.println(line);
                }

            } catch (MalformedURLException e)
            {
                e.printStackTrace();

            } catch (IOException e)
            {
                e.printStackTrace();

            }

我尝试过更改行

try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")))

try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)))

try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")))

不幸的是,这个问题仍然存在。我真的很感激任何提示,所以我可以解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:0)

要分析您的问题,我尝试通过curl从给定的网址下载 (使用选项-i查看HTTP响应标题行)并得到:

Cache-Control: private
Content-Type: application/json; charset=utf-8
Content-Encoding: gzip
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Credentials: false
X-Content-Type-Options: nosniff
Date: Sat, 21 Apr 2018 21:48:42 GMT
Content-Length: 85

▒VJ-*▒/▒▒LQ▒210ЁrsS▒▒▒S▒▒▒▒3KR2▒▒R
 K3▒RS▒`J▒sA▒I▒)▒▒E@NIj▒R-g▒▒PP^C

Content-Encoding: gzip行告诉您内容是gzip压缩的。

因此,在Java程序中,您需要gzip-un压缩内容 您只需更换行

即可完成此操作
is = url.openStream();

is = new GZIPInputStream(url.openStream());

更好的方法是获得实际的内容编码 并根据它决定是否需要解压缩内容:

URLConnection connection = url.openConnection();
is = connection.getInputStream();
String contentEncoding = connection.getContentEncoding();
if (contentEncoding.equals("gzip"))
    is = new GZIPInputStream(is);