我想讀一個JSON字符串:URLConnection的字符編碼
{
"also_known_as": [
"Сильвестр Сталлоне"
],
"birthday": "1946-07-06",
"deathday": "",
}
通過HTTP。
我有以下代碼:
URL url = new URL("url");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");//connection.setRequestProperty("Accept-Charset", "ISO-8859-1");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringWriter writer = new StringWriter();
while((line=reader.readLine())!=null){
writer.write(line);
}
reader.close();
writer.close();
connection.disconnect();
System.out.println(writer.toString());
但它打印字符串中控制檯:
{
"also_known_as": [
"СильвеÑ?Ñ‚Ñ€ Сталлоне"
],
"birthday": "1946-07-06",
"deathday": "",
}
我也曾嘗試:
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));//BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "ISO-8859-1"));
,但沒有運氣。
我的問題是我怎麼可以設置URLConnection的字符編碼?
任何信息對我都很有幫助。
問候。
使用Apache IOUtils我已經試過這樣:
StringWriter writer = new StringWriter();
IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
但它打印在Eclipse的控制檯相同的結果。
使用Apache的HttpClient:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("http://api.themoviedb.org/3/person/16483?api_key=23e89da030a0ee8b25aaed20950a0c25");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
StringWriter writer = new StringWriter();
IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
System.out.println(writer.toString());
相同的結果。
你要編碼的BufferedReader或StringWriter的適當字符集 – mKorbel 2012-03-03 19:47:01
@mKorbel我曾嘗試使用IOUtils。我編輯了我的答案。但它也是一樣的結果。 :( – 2012-03-03 20:08:17
你確定這不是你的控制檯的字符集設置不正確嗎? – 2012-03-03 20:20:58