//首先工具類 public class MyX509TrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } //WeixinUtil工具類 獲取token須要用到的 public class WeixinUtil { private static Logger log = LoggerFactory.getLogger(WeixinUtil.class); /** * 發起https請求並獲取結果 * * @param requestUrl 請求地址 * @param requestMethod 請求方式(GET、POST) * @param outputStr 提交的數據 * @return JSONObject(經過JSONObject.get(key)的方式獲取json對象的屬性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 建立SSLContext對象,並使用咱們指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 從上述SSLContext對象中獲得SSLSocketFactory對象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 設置請求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 當有數據須要提交時 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意編碼格式,防止中文亂碼 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 將返回的輸入流轉換成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 釋放資源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.parseObject(buffer.toString()); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return jsonObject; } } //AccessToken public class AccessToken { // 獲取到的憑證 private String token; // 憑證有效時間,單位:秒 private int expiresIn; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public int getExpiresIn() { return expiresIn; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } } //在獲取小程序碼以前,首先獲取token public String getToken(){ Locale locale = new Locale("en", "US"); ResourceBundle resource = ResourceBundle.getBundle("你的配置文件路徑", locale); //讀取屬性文件 String appId = resource.getString("appId"); //開發者設置中的appId String secret = resource.getString("appSecret"); //開發者設置中的appSecret AccessToken accessToken = null; ////請求地址 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret; JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null); // 若是請求成功 if (null != jsonObject) { try { accessToken = new AccessToken(); accessToken.setToken(jsonObject.getString("access_token")); accessToken.setExpiresIn(jsonObject.getIntValue("expires_in")); } catch (JSONException e) { accessToken = null; // 獲取token失敗 logger.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg")); } } String token = accessToken.getToken(); return token; } //下面在獲取小程序碼 public Map getQrCode(String accessToken) { RestTemplate rest = new RestTemplate(); InputStream inputStream = null; OutputStream outputStream = null; try { String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken; Map<String, Object> param = new HashMap<>(); //param.put("path", "pages/要跳轉小程序的路徑")//有限 //param.put("page", "pages/index/index"); //無限 param.put("width", 430); param.put("auto_color", false); Map<String, Object> line_color = new HashMap<>(); line_color.put("r", 0); line_color.put("g", 0); line_color.put("b", 0); param.put("line_color", line_color); logger.info("調用生成微信URL接口傳參:" + param); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); HttpEntity requestEntity = new HttpEntity(JSON.toJSONString(param), headers); ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]); logger.info("調用小程序生成微信永久小程序碼URL接口返回結果:" + entity.getBody()); byte[] result = entity.getBody(); logger.info(Base64.encodeBase64String(result)); inputStream = new ByteArrayInputStream(result); File file = new File("保存到本地的路徑"); if (!file.exists()) { file.createNewFile(); } outputStream = new FileOutputStream(file); int len = 0; byte[] buf = new byte[1024]; while ((len = inputStream.read(buf, 0, 1024)) != -1) { outputStream.write(buf, 0, len); } outputStream.flush(); } catch (Exception e) { logger.error("調用小程序生成微信永久小程序碼URL接口異常", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }