您的位置:首页 > 移动开发 > 微信开发

微信开发时遇到的UrlConnection乱码问题的处理

2016-10-21 10:32 141 查看
昨天做一个微信的模板消息推送的功能,功能倒是很快写完了,我本地测试微信收到的推送消息是正常的,但是一部署到服务器后微信收到的推送消息就变成乱码了。



为了找到原因,做了很多测试,最后得出结论,因为微信那边平台使用的是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     }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: