1. 程式人生 > >呼叫微信小程式API生成二維碼 並轉base64存資料庫

呼叫微信小程式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);
    }
}