微信小程序> java开发微信小程序——二维码生成

java开发微信小程序——二维码生成

浏览量:535 时间: 来源:persistenceヾ(◍°∇°◍)ノ

https://blog.csdn.net/persistencegoing/article/details/84376427

 

工具类:
public class TwoCode {
    
    /*
     * 获取 token
   * 普通的 get 可获 token
     */
    public  static String getToken() {
        try {
 
            Map<String, String> map = new LinkedHashMap<String, String>();
            map.put("grant_type", "client_credential");
            map.put("appid", Contants.appId);//改成自己的appid
            map.put("secret", Contants.secret);
 
            String rt = UrlUtil.sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
            
            System.out.println("what is:"+rt);
            JSONObject json = JSONObject.parseObject(rt);
 
            if (json.getString("access_token") != null || json.getString("access_token") != "") {
                return json.getString("access_token");
            } else {
                return null;
            }
       } catch (Exception e) {
   
            e.printStackTrace();
            return null;
        }
 
    }
    
    /*
     * 获取 二维码图片
   * 
     */
    public static String getminiqrQr( String accessToken,HttpServletRequest request) {
        String p=request.getSession().getServletContext().getRealPath("/");
        String codeUrl=p+"/twoCode.png";
        String twoCodeUrl="twoCode.png";
         try
         {
             URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
             HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
             httpURLConnection.setRequestMethod("POST");// 提交模式
             // conn.setConnectTimeout(10000);//连接超时 单位毫秒
             // conn.setReadTimeout(2000);//读取超时 单位毫秒
             // 发送POST请求必须设置如下两行
             httpURLConnection.setDoOutput(true);
             httpURLConnection.setDoInput(true);
             // 获取URLConnection对象对应的输出流
             PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
             // 发送请求参数
             JSONObject paramJson = new JSONObject();
             paramJson.put("scene", "1234567890");
             paramJson.put("path", "pages/index?query=1");
             paramJson.put("width", 430);
             paramJson.put("is_hyaline", true);
             paramJson.put("auto_color", true);
             /**
              * line_color生效
              * paramJson.put("auto_color", false);
              * JSONObject lineColor = new JSONObject();
              * lineColor.put("r", 0);
              * lineColor.put("g", 0);
              * lineColor.put("b", 0);
              * paramJson.put("line_color", lineColor);
              * */
 
             printWriter.write(paramJson.toString());
             // flush输出流的缓冲
             printWriter.flush();
             //开始获取数据
             BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
             OutputStream os = new FileOutputStream(new File(codeUrl));
             int len;
             byte[] arr = new byte[1024];
             while ((len = bis.read(arr)) != -1)
             {
                 os.write(arr, 0, len);
                 os.flush();
             }
             os.close();
         }
         catch (Exception e)
         {
             e.printStackTrace();
         }
        return twoCodeUrl;
    }
}
2.controller层:

/**
     * 接收二维码
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value="/twoCode",method=RequestMethod.POST,produces="text/html;charset=utf-8")
    @ResponseBody
    public Object twoCode(HttpServletRequest request) throws IOException{
        JSONObject data=new JSONObject();
        String accessToken = TwoCode.getToken();
        System.out.println("accessToken;"+accessToken);
        String twoCodeUrl = TwoCode.getminiqrQr(accessToken,request);
        data.put("twoCodeUrl", twoCodeUrl);
        return data;
        
    }
3.http工具:
public class UrlUtil {
      /** 
    * 向指定 URL 发送POST方法的请求 
    * 
    * @param url 发送请求的 URL 
    * @param param 请求参数 
    * @return 所代表远程资源的响应结果 
    */
    public static String sendPost(String url, Map<String, ?> paramMap) { 
       PrintWriter out = null; 
       BufferedReader in = null; 
       String result = ""; 
         
       String param = ""; 
    Iterator<String> it = paramMap.keySet().iterator(); 
      
    while(it.hasNext()) { 
      String key = it.next(); 
      param += key + "=" + paramMap.get(key) + "&"; 
    } 
      
       try { 
         URL realUrl = new URL(url); 
         // 打开和URL之间的连接 
         URLConnection conn = realUrl.openConnection(); 
         // 设置通用的请求属性 
         conn.setRequestProperty("accept", "*/*"); 
         conn.setRequestProperty("connection", "Keep-Alive"); 
         conn.setRequestProperty("Accept-Charset", "utf-8"); 
         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(); 
         // 定义BufferedReader输入流来读取URL的响应 
         in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); 
         String line; 
         while ((line = in.readLine()) != null) { 
           result += line; 
         } 
       } catch (Exception e) { 
        System.out.println(e); 
       } 
       //使用finally块来关闭输出流、输入流 
       finally{ 
         try{ 
           if(out!=null){ 
             out.close(); 
           } 
           if(in!=null){ 
             in.close(); 
           } 
         } 
         catch(IOException ex){ 
           ex.printStackTrace(); 
         } 
       } 
       return result; 
     } 
}
 

 

希望大家关注我一波,防止以后迷路,有需要的可以加群讨论互相学习java ,学习路线探讨,经验分享与java求职     

群号:721 515 304

小程序

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎