Skip to content

Windows 上的 Java 字符编码问题

通过 HTTP 调用接口返回的中文,在本地调试时是正常的,但是在服务器上部分中文乱码。

操作系统:Windows Server 2008 R2 Enterprise

HTTP 请求代码

这边修改 http 请求的编码格式没有效果。

java
//创建连接
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url
				.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", APPLICATION_JSON);

connection.connect();

//POST 请求
DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());

out.writeBytes(json);
out.flush();
out.close();

//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
		lines = new String(lines.getBytes(), "utf-8");
		sb.append(lines);
}

reader.close();
// 断开连接
connection.disconnect();

解决方案

在系统环境变量中增加一个变量,变量名为: JAVA_TOOL_OPTIONS,变量值为:-Dfile.encoding=UTF-8

但是导致了另外一个问题:控制台打印的中文变成了乱码。

=.=|||

应该是因为 Windows 控制台的默认编码为 936(也就是 BGK,通过 chcp 命令查看)导致的。

参照