微信公众号开发调用微信接口得到的参数中文变成乱码问题

  做过微信开发的人应该都会接触到授权登录、获取用户信息等操作,比如获取用户信息,腾讯要求以get请求提交,返回的是json字符串。

通常我们使用的方法是用HttpURLConnection去调用接口,打开http连接,从连接读取返回的参数。

但是有时候(本人的开发环境没问题,部署到linux服务器上后存在乱码问题)接收到的json字符串中文字符变成乱码。
以下是我的代码

try {
  System.out.println("访问GET请求:" + url1);
  HttpURLConnection httpConn = null;
  BufferedReader in = null;
  try {
    URL url = new URL(url1);
    httpConn = (HttpURLConnection) url.openConnection();
    // 读取响应
    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
      StringBuffer content = new StringBuffer();
      String tempStr = "";       in = new BufferedReader(new InputStreamReader(     httpConn.getInputStream()));       while ((tempStr = in.readLine()) != null) {     content.append(tempStr);
      }
      return JSONObject.fromObject(content.toString());     } else {   throw new Exception("请求出现了问题!");
    }   } catch (IOException e) {     e.printStackTrace();   } finally {       in.close();
      httpConn.disconnect();   }  } catch (Exception e) {     e.printStackTrace();
}

 其实这种做法只需要从输入流读取参数的时候指定读取的数据的编码格式即可,代码为

in = new BufferedReader(new InputStreamReader(
    httpConn.getInputStream(),"UTF-8"));

 如此上述乱码问题解决。

还有,在我们发送POST请求时,如调用自定义菜单、推送消息等接口时,需要发送参数,代码如下

URL realUrl = new URL(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)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();

 其中param是参数,这样param中存在中文参数时,也会出现乱码,比如公众号的自定义菜单变成乱码等。解决办法与上面类似

out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));

 将输出流中的参数指定编码格式,乱码问题解决。

原文地址:https://www.cnblogs.com/xiao-tao/p/6028028.html