JAVA线上项目遇到JVM环境,引起字符编码转换无效的问题
问题描述:线上的项目需要发送请求访问接口,用eclipse运行没有任何问题(因为eclipse环境设置的是UTF-8),但用maven打成jar包运行就会出现编码的问题(因为打包的JVM环境是gb2312的)。
单纯使用
byte[] bytes = rs.getBytes();
String str = new String(bytes, "gb2312");
无法成功的转换
解决办法:数据请求不使用字节做转换,而是需要在流的层面上转换
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-type", "application/json;charset=utf-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//在流的层面上转换
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
PrintWriter out = new PrintWriter(writer);
out.print(JSONObject.fromObject(param));
// flush输出流的缓冲
out.flush();
conn.connect();
这样就可以成功发送接口请求