如何使用 JAVA 在 HTTP GET 中设置 utf
how to set utf in HTTP GET, using JAVA
我在 Get 请求的响应中收到特殊字符,如“ñ”或“á、é”等。代码是下一个:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
BufferedReader b_r = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String data = b_r.readLine();
如何设置 utf-8 以接收正确的字符?
理想情况下,根本不要使用此代码 - 使用接受 InputStream
的 JSON 解析器,而不是逐行读取它。
如果需要,请将 UTF-8 指定为 InputStreamReader
的编码,因为您目前仅使用平台默认编码:
BufferedReader b_r = new BufferedReader(
new InputStreamReader((connection.getInputStream(), StandardCharsets.UTF_8)));
这是假设它真的 是 UTF-8 - 它应该是,如果它是 JSON。 (如果服务器 没有 发送 UTF-8,您应该尝试解决这个问题。)
我在 Get 请求的响应中收到特殊字符,如“ñ”或“á、é”等。代码是下一个:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
BufferedReader b_r = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String data = b_r.readLine();
如何设置 utf-8 以接收正确的字符?
理想情况下,根本不要使用此代码 - 使用接受 InputStream
的 JSON 解析器,而不是逐行读取它。
如果需要,请将 UTF-8 指定为 InputStreamReader
的编码,因为您目前仅使用平台默认编码:
BufferedReader b_r = new BufferedReader(
new InputStreamReader((connection.getInputStream(), StandardCharsets.UTF_8)));
这是假设它真的 是 UTF-8 - 它应该是,如果它是 JSON。 (如果服务器 没有 发送 UTF-8,您应该尝试解决这个问题。)