微信小程序推送乱码问题
2018-09-08 今天在做微信消息推送时,消息内容乱码,如下图:
首先,想到的是idea的编码方式,在file–>setting–>editor–>file encodings下下拉框均选择utf-8
其次,想到的是string字符串转码问题,通过new String(str.getBytes(“gbk”),“UTF-8”);在微信上显示的变为了问号。???
然后,猜测会不会是在拼接url时中文编码问题,于是使用URLEncoder.encode(“内容”);在微信上显示的变为了各种百分号。。。。
最后,在百度上搜索“微信消息推送乱码”,参考:java微信 客服接口-发消息 中文乱码 成功解决问题
将原有代码 pw = new PrintWriter(connection.getOutputStream());
改为
OutputStreamWriter outWriter =
new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
pw = new PrintWriter(outWriter);
全部代码如下:
String result = "";
PrintWriter pw = null;
BufferedReader br = null;
try {
URL realUrl = new URL(requestUrl);
HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
// 获取URLConnection对象对应的输出流
OutputStreamWriter outWriter