调用微信小程序API生成二维码 并转base64存数据库

public class GeneralTokenUtil {

    private static final String appid = "";
    private static final String grant_type = "";

    // 获取token值
    public static String getToken(String cmpId) {
        String line = "";
        String access_token = "";
        String qr = "";
        try {
            String str = "https://api.weixin.qq.com/cgi-bin/token?appid=" + appid + "&grant_type=" + grant_type;
            URL url = new URL(str);
            // 得到connection对象。
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 连接
            connection.connect();
            // 得到响应码
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 得到响应流
                InputStream inputStream = connection.getInputStream();
                // 获取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                while ((line = reader.readLine()) != null) {
                    access_token = line;
                    System.out.println(line);
                }
                JSONObject jsonObject = JSONObject.fromObject(access_token);
                String name = jsonObject.getString("access_token");
                Map map = new HashMap();
                map.put("scene", cmpId);
                map.put("page", "pages/welcome/welcome");
                String date = JSONObject.fromObject(map).toString();// 转化成json
                String strToken = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + name;
                // qr = getQR(name,cmpId);
                qr = httpPostWithJSON(strToken, date, cmpId);
                reader.close();
                // 该干的都干完了,记得把连接断了
                connection.disconnect();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return qr;
    }

    public static String httpPostWithJSON(String url, String json, String id) throws Exception {
        String result = null;
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

        StringEntity se = new StringEntity(json);
        se.setContentType("application/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "UTF-8"));
        httpPost.setEntity(se);
        // httpClient.execute(httpPost);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
//            if (resEntity != null) {
                InputStream instreams = resEntity.getContent();
//                System.out.println(instreams);
//                String uploadSysUrl = "E://erweima/";
//                File saveFile = new File(uploadSysUrl + id + ".png");
//                // 判断这个文件(saveFile)是否存在
//                if (!saveFile.getParentFile().exists()) {
//                    // 如果不存在就创建这个文件夹
//                    saveFile.getParentFile().mkdirs();
//                }
//                result = saveToImgByInputStream(instreams, uploadSysUrl, id + ".png");
                result = getBase64FromInputStream(instreams);
                result = "data:image/png;base64,"+result;
//            }
        }
        httpPost.abort();
        return result;
    }

    /*
     * @param instreams 二进制流
     * 
     * @param imgPath 图片的保存路径
     * 
     * @param imgName 图片的名称
     * 
     * @return 1:保存正常 0:保存失败
     */
    public static String saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) {
        String path = "";
        int stateInt = 1;
        if (instreams != null) {
            try {
                File file = new File(imgPath + imgName);// 可以是任何图片格式.jpg,.png等
                FileOutputStream fos = new FileOutputStream(file);

                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
                try {
                    instreams.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
         return path;
    }
    
    /**
     * 
     * 转base64
     * 
     * */
     public static String getBase64FromInputStream(InputStream in) {
            // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
            byte[] data = null;
            // 读取图片字节数组
            try {
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = in.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                data = swapStream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return new String(Base64.encodeBase64(data));
        }


    public static void main(String[] args) {
        String token = getToken("1");
        System.out.println(token);
    }
}

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值