微信-生成小程二维码

1.生成二维码的代码片段

private String getQRCode(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("r", 0);
        map.put("g", 162);
        map.put("b", 232);
        HttpsUtil client = new HttpsUtil();
        try {
            String token = wxAccessTokenProvider.getAccessToken();
            
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token 
            
            File local = client.getWXACodeImg(url, id, 360, false, map,
                    "二维码临时保存的位置");
                    
             //把文件上传到了阿里云,可以改为保存到本地的,并返回能访问的路径       
            String smallUrl = ossFileUploadController.uploadQrCodeToOss(local, false, false);
            return smallUrl;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("二维码获取失败");
        }
        return null;
    }

2.构建请求客户端

private CloseableHttpClient client = null;

//这里通过构造器,创建了httpClient。可以修改为别的方式httpClient请求方式
public HttpsUtil() {
        RequestConfig requestConfig = RequestConfig.custom()
        		// connectionRequestTimeout 指从连接池获取连接的超时时间 (timeout requesting a connection from the connection manager)
        		.setConnectionRequestTimeout(100)
        		// connectTimeout 指客户端和服务器建立连接的超时时间 (timeout until a connection is established)
        		.setConnectTimeout(1000)
        		// socketTimeout 指客户端从服务器读取数据的超时时间 (timeout for waiting for data)
        		.setSocketTimeout(3000)
        		.build();
        
        client = HttpClients.custom()
        		.setDefaultRequestConfig(requestConfig)
        		// The ConnectionTimeToLive determines the maximum age of a connection (after which it will be closed), 
        		// regardless of when the connection was last used
        		// 参考: https://stackoverflow.com/questions/31566851/setconnecttimeout-vs-setconnectiontimetolive-vs-setsockettimeout
        		.setConnectionTimeToLive(60 * 1000, TimeUnit.MILLISECONDS)
        		// 默认只 2, 请求单个域名支持的最大连接
        		.setMaxConnPerRoute(200)
        		// 默认值 20, 最大总连接
        		.setMaxConnTotal(400)
        		// 设置重试次数, 默认是3次; requestSentRetryEnabled==false 如果请求已成功发送则不再重试. 
        		// 接收到response表示请求发送成功, 参考 HttpRequestExecutor#doSendRequest - context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE)
        		.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
        		.build();
    }

//请求微信获取生成的小程序二维码
public File getWXACodeImg(String url, Integer inviteCode, int size, boolean autoColor, Object lineColor,
                              String tempQRCodeDir) throws UnsupportedOperationException, IOException, Exception {

        HttpPost post = new HttpPost(url);
        setHeaderKeepAlive(post);
        Map<String, Object> map = new HashMap<>();
        map.put("scene", inviteCode);
        map.put("width", size);
        map.put("auto_color", autoColor);
        map.put("line_color", lineColor);
        String json = Convertor.toJson(map);
        logger.info(json);
//        System.out.println(json);
        HttpEntity entity = new StringEntity(json, Constants.CS_UTF_8);
        post.setEntity(entity);

        CloseableHttpResponse response = client.execute(post);

        InputStream inStream = response.getEntity().getContent();
        byte data[] = readInputStream(response.getEntity().getContent());
//		inStream.read(data); // 读取该数据
        inStream.close();

        if (data.length < 1024 * 10) {
            throw new BusinessException(new String(data));
        } else {
            File path = new File(tempQRCodeDir);
            if (!path.exists()) {
                path.mkdirs();
            }
            String file = tempQRCodeDir + "/"+ IDGenerator.getUUID()+ System.currentTimeMillis() + ".jpg";
            FileOutputStream os = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            InputStream in = new ByteArrayInputStream(data);
            byte[] b = new byte[1024];
            int nRead = 0;
            while ((nRead = in.read(b)) != -1) {
                os.write(b, 0, nRead);
            }
            os.flush();
            os.close();
            in.close();

            return new File(file);
        }
    }

3.获取accessToken

//请求获取token
 public String getWxToken(){
     String json = "";
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ "小程序的appId" + "&secret=" + "小程序的秘钥";
            json = httpUtil.get(url);
        } catch (Exception e) {
            throw new SystemException("获取微信接口accessToken网络异常", e);
        }            
    return json ;
}      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值