如何使用JAVA在HTTP GET中设置utf

ign*_*zzo 2 java string json utf-8 json-deserialization

我在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();
Run Code Online (Sandbox Code Playgroud)

如何设置utf-8以接收正确的字符?

Jon*_*eet 5

理想情况下,根本不要使用此代码 - 使用接受a的JSON解析器InputStream,而不是逐行读取.

如果需要,请指定UTF-8作为编码InputStreamReader,因为您目前只使用平台默认编码:

BufferedReader b_r = new BufferedReader(
    new InputStreamReader((connection.getInputStream(), StandardCharsets.UTF_8)));
Run Code Online (Sandbox Code Playgroud)

这假设它确实 UTF-8 - 它应该是,如果它是JSON.(如果服务器没有发送UTF-8,你应该尝试修复它.)