[英]Extracting text from InputStreamReader not working in UTF-8
我正在嘗試閱讀以下API文本頁面:
使用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")))
不幸的是,問題仍然存在。 我真的很感謝任何提示,以便我可以解決此問題。 謝謝。
為了分析您的問題,我嘗試通過curl
從給定的URL下載(帶有-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解壓縮內容。
您只需替換行即可
is = url.openStream();
與
is = new GZIPInputStream(url.openStream());
更好的方法是獲取實際的Content-Encoding,並根據此決定是否解壓縮內容:
URLConnection connection = url.openConnection();
is = connection.getInputStream();
String contentEncoding = connection.getContentEncoding();
if (contentEncoding.equals("gzip"))
is = new GZIPInputStream(is);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.