微信开发时遇到的UrlConnection乱码问题的处理
2016-10-21 10:32
141 查看
昨天做一个微信的模板消息推送的功能,功能倒是很快写完了,我本地测试微信收到的推送消息是正常的,但是一部署到服务器后微信收到的推送消息就变成乱码了。
为了找到原因,做了很多测试,最后得出结论,因为微信那边平台使用的是UTF-8的编码,我本地使用的也是UTF-8编码,但是我们公司的linux服务器上使用的却是GB18030的编码,(可以使用这行代码获取文件运行环境的编码方式:System.getProperty("file.encoding");)。所以出现了乱码,现在把调用消息模板后的发送POST请求的代码修改如下,就没有问题了:
为了找到原因,做了很多测试,最后得出结论,因为微信那边平台使用的是UTF-8的编码,我本地使用的也是UTF-8编码,但是我们公司的linux服务器上使用的却是GB18030的编码,(可以使用这行代码获取文件运行环境的编码方式:System.getProperty("file.encoding");)。所以出现了乱码,现在把调用消息模板后的发送POST请求的代码修改如下,就没有问题了:
1 /** 2 * 向指定 URL 发送POST方法的请求 3 * 4 * @param url 发送请求的 URL 5 * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 6 * @return 所代表远程资源的响应结果 7 */ 8 public static String sendPost(String url, String param) { 9 //PrintWriter out = null;//原来使用的输出流 10 OutputStreamWriter out = null;//修改后的 11 BufferedReader in = null; 12 String result = ""; 13 try { 14 URL realUrl = new URL(url); 15 //打开和URL之间的连接 16 URLConnection conn = realUrl.openConnection(); 17 //设置通用的请求属性 18 conn.setRequestProperty("accept", "*/*"); 19 conn.setRequestProperty("connection", "Keep-Alive"); 20 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 21 conn.setRequestProperty("Charset", "UTF-8"); 22 //发送POST请求必须设置如下两行 23 conn.setDoOutput(true); 24 conn.setDoInput(true); 25 //获取URLConnection对象对应的输出流 26 //原来的,这句代码引起字符集的变化,如果项目不是UTF-8就会转成当前环境的编码 27 //out = new PrintWriter(conn.getOutputStream()); 28 //修改后的,这里可以设定字符集 29 out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); 30 //发送请求参数 31 //out.print(param);//原来的 32 out.write(param);//修改后的 33 //flush输出流的缓冲 34 out.flush(); 35 //定义BufferedReader输入流来读取URL的响应 36 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8")); 37 String line; 38 while ((line = in.readLine()) != null) { 39 result += line; 40 } 41 } catch (Exception e) { 42 System.out.println("发送 POST 请求出现异常!"+e); 43 e.printStackTrace(); 44 } 45 //使用finally块来关闭输出流、输入流 46 finally{ 47 try{ 48 if(out!=null){ 49 out.close(); 50 } 51 if(in!=null){ 52 in.close(); 53 } 54 } 55 catch(IOException ex){ 56 ex.printStackTrace(); 57 } 58 } 59 return result; 60 }
相关文章推荐
- 遇到了一个HttpURLConnection乱码问题:结果是JVM file.encoding错误
- 处理VC开发的webservice在C#.NET中中文乱码问题
- 微信公众帐号开发。大家是用框架还是自己写的流程。现在遇到若干问题。请教各路大仙 - V2EX
- 处理URL传递中文乱码问题
- HttpUrlConnection post方法传递中文乱码问题
- HttpUrlConnection post方法传递中文乱码问题
- 处理URL传递中文乱码问题
- Web开发中的中文处理及乱码问题解决
- 处理URL传递中文乱码问题
- HttpURLConnection 处理乱码办法
- httpurlconnection post 和GET 分别传递2个参数给后台,返回JSON 解决乱码问题
- JSP开发中遇到中文处理问题汇总文章
- 在做Asp.Net开发的时候,经常会遇到页面乱码的问题,下面是在网上收集的相关资料,请大家参考:
- 解决HttpUrlConnection乱码问题
- JAVAEE开发中的问题--乱码处理
- 在utf8下php处理url传送数据的的乱码问题
- Ajax 开发中遇到的乱码问题
- 处理URL传递中文乱码问题Pthill转载
- jQuery中getScript方法引入外部js文件,乱码处理(自己遇到的问题)
- 处理URL传递中文乱码问题