在使用HttpURLConnection访问其他系统接口推送数据时出现了中文乱码问题,使用OutputStream 推送字节流,对方系统解析中文出现乱码,无法通过校验,改用PrintWriter推送字符流,成功解析!~贴代码记录一下!!~
// 接口参数
Map<String, Object> param = new HashMap<String, Object>();
//接口地址
String url = "";
URL postUrl = new URL(url);
//跳过证书校验
if("https".equalsIgnoreCase(postUrl.getProtocol())){
SslUtils.ignoreSsl();
}
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Charset", "UTF-8");
connection.setConnectTimeout(100000);
connection.setReadTimeout(100000);
connection.setRequestMethod("POST");
//这里是使用form形式推送的数据,json同理
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//OutputStream out = connection.getOutputStream(); 方法1
PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"utf-8"));//方法2
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> entry : param.entrySet()) {
sb.append(entry.getKey() + "=" + entry.getValue());
sb.append("&");
}
String sb1 = sb.toString();
if (sb1.endsWith("&")) {
sb1 = sb1.substring(0, sb1.length() - 1);
}
//out.write(sb1.toString().getBytes()); 方法1
out.write(sb1.toString());//方法2
out.flush();
out.close();