[問題] 關於 UTF-8 編碼轉換問題

看板java作者 (最難學會的事)時間10年前 (2015/07/06 21:04), 編輯推噓1(1010)
留言11則, 4人參與, 最新討論串1/1
我需要呼叫一個 RESTful API 來取得 JSON 格式資料, 資料為中文,編碼為 UTF-8,目前使用 HttpURLConnection 來處理。 但碰到一個問題,所取得的資料編碼為 UTF-8 沒錯,並不是亂碼, 不過所看到的資料都呈現 \u65e5\u85e5\u672c\u8216 之類的格式, 看的到 UTF-8 的編碼方式,卻無法轉成中文, 不知道有沒有人知道如何處理? 或是有沒有比 HttpURLConnection 更好用的 package? 先感謝大家幫忙 <(_ _)> 程式碼如下: String url = "http://xxx/xxx"; // RESTful API 網址 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); con.setRequestProperty("Accept", "application/json;charset=UTF-8"); con.connect(); OutputStream out = con.getOutputStream(); out.write(parameters().getBytes()); // 傳遞某些參數過去 out.close(); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); con.disconnect(); -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.248.119.171 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1436187889.A.443.html

07/06 21:53, , 1F
就去找個可處理\uXXXX的library或是自己寫
07/06 21:53, 1F

07/06 21:57, , 2F
例如apache的StringEscapeUtils
07/06 21:57, 2F

07/06 21:58, , 3F
會拿到\uXXXX就是資料本來就長這樣,跟URLConnection沒關係
07/06 21:58, 3F

07/06 23:55, , 4F
感謝,我去找找 StringEscapeUtils
07/06 23:55, 4F

07/07 01:24, , 5F
不想加新的lib的話可以用Properties的load()方法 把讀進
07/07 01:24, 5F

07/07 01:25, , 6F
來的json先組成一個property的string再用StringReader讀
07/07 01:25, 6F

07/07 01:26, , 7F
但是有一些不能用的字元的話要自己做property的escape
07/07 01:26, 7F

07/07 10:15, , 8F
感謝,我兩種方法都來查查看!!!
07/07 10:15, 8F

07/07 20:29, , 9F
日藥本舖
07/07 20:29, 9F

07/07 20:36, , 10F
07/07 20:36, 10F

07/08 11:14, , 11F
成功了,感謝樓上各位
07/08 11:14, 11F
文章代碼(AID): #1LcdpnH3 (java)
文章代碼(AID): #1LcdpnH3 (java)