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

工具类:
public class TwoCode {
	
	/*
     * 获取 token
   * 普通的 get 可获 token
     */
    public  static String getToken() {
        try {

            Map map = new LinkedHashMap();
            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 paramMap) { 
	   PrintWriter out = null; 
	   BufferedReader in = null; 
	   String result = ""; 
	     
	   String param = ""; 
	Iterator 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; 
	 } 
}

你可能感兴趣的:(微信小程序)