InputStream讀JSON資料時亂碼
阿新 • • 發佈:2019-02-02
注意:本文案例資訊:IDE是eclipse,post請求伺服器,返回JSON資料。
先上程式碼:
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
String result = "";
while ((line = reader.readLine()) != null) {
result += line;
}
System.out.println(result);
亂碼如下:
在網上查找了很久,試過了如下方法,均無效:
1.修改Windows->Preferences->Workspace->text file encoding成utf-8或GBK或GBK2312.
2.設定專案的run configurations:右鍵專案名->run as->run configurations->Arguments->VM arguments:-Dfile.encoding=UTF-8或GBK或GBK2312,Common裡面選擇Encoding也為對應的(如果下拉框沒有,手動輸入就行了)
把上邊附的程式碼替換成:
InputStreamReader is = new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"); StringBuilder sb = new StringBuilder(); char[] cbuf = new char[1024]; int len = 0; while ((len = is.read(cbuf)) != -1) { sb.append(cbuf, 0, len); } System.out.println(sb.toString());
輸出: