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

工具类:
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; 
	 } 
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
生成微信小程序二维码可以使用微信官方提供的API,具体可以参考微信官方文档。以下是使用Java实现生成微信小程序二维码的示例代码: ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class WeChatQRCode { public static void main(String[] args) throws IOException { // 小程序 appid String appid = "your appid"; // 小程序 appsecret String appsecret = "your appsecret"; // 获取 access_token 的接口地址 String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret; // 获取小程序码的接口地址 String qrcodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token="; // 保存二维码的本地文件路径 String filePath = "qrcode.jpg"; // 发送获取 access_token 的请求 URL url = new URL(tokenUrl); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); byte[] buffer = new byte[1024]; int len; StringBuilder sb = new StringBuilder(); while ((len = in.read(buffer)) != -1) { sb.append(new String(buffer, 0, len)); } in.close(); String accessToken = sb.toString().split("\"")[3]; // 发送获取小程序码的请求 url = new URL(qrcodeUrl + accessToken); conn = url.openConnection(); in = conn.getInputStream(); FileOutputStream out = new FileOutputStream(filePath); while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); System.out.println("小程序码已保存到:" + filePath); } } ``` 需要注意的是,生成小程序码的接口有一些限制,例如必须是已发布的小程序二维码有效期为7天等,具体请参考微信官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值