java微信 客服接口-发消息 中文乱码

时间:2023-03-09 08:55:09
java微信 客服接口-发消息 中文乱码
  1. /**
  2. * 向指定 URL 发送POST方法的请求
  3. *
  4. * @param url
  5. *            发送请求的 URL
  6. * @param param
  7. *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  8. * @return 所代表远程资源的响应结果
  9. */
  10. public static String sendPost(String url, String param) {
  11. PrintWriter out = null;
  12. BufferedReader in = null;
  13. String result = "";
  14. try {
  15. URL realUrl = new URL(url);
  16. // 打开和URL之间的连接
  17. URLConnection conn = realUrl.openConnection();
  18. //设置通用的请求属性
  19. conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
  20. // 发送POST请求必须设置如下两行
  21. conn.setDoOutput(true);
  22. conn.setDoInput(true);
  23. // 获取URLConnection对象对应的输出流
  24. OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
  25. out = new PrintWriter(outWriter);
  26. // 发送请求参数
  27. out.print(param);
  28. // flush输出流的缓冲
  29. out.flush();
  30. // 定义BufferedReader输入流来读取URL的响应
  31. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  32. String line;
  33. while ((line = in.readLine()) != null) {
  34. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));result += line;
  35. }
  36. } catch (Exception e) {
  37. System.out.println("发送 POST 请求出现异常!"+e);
  38. e.printStackTrace();
  39. }
  40. //使用finally块来关闭输出流、输入流
  41. finally{
  42. try{
  43. if(out!=null){
  44. out.close();
  45. }
  46. if(in!=null){
  47. in.close();
  48. }
  49. }
  50. catch(IOException ex){
  51. ex.printStackTrace();
  52. }
  53. }
  54. return result;
  55. }
  1. /**
  2. * 普通文本消息,需用户在48h与公共帐号有互动
  3. * 微信公共账号发送给账号
  4. * @param content 文本内容
  5. * @param toUser(OPENID) 微信用户
  6. * @return
  7. */
  8. public static void sendTextMessageToUser(HttpServletRequest request,String content,String toUser){
  9. String json = "{\"touser\": \""+toUser+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+content+"\"}}";
  10. //获取access_token
  11. String accessToken = getAccessToken(request);
  12. //发送模版消息给指定用户
  13. String action = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
  14. System.out.println("json:"+json);
  15. try {
  16. String result = HttpJsonUtil.sendPost(action, json);
  17. System.out.println(result);
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. }

java微信 客服接口-发消息 中文乱码

我自己都不知道在这个地方倒下了多少次了:

关键代码:

// 获取URLConnection对象对应的输出流
OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
out = new PrintWriter(outWriter);

乱码时候的写法是:

in = new BufferedReader(new InputStreamReader(conn.getInputStream()));