tip
:經過該接口,僅能生成已發佈的小程序的二維碼。tip
:能夠在開發者工具預覽時生成開發版的帶參二維碼。tip
:接口A加上接口C,總共生成的碼數量限制爲100,000,請謹慎調用。tip
: POST 參數須要轉成 json 字符串,不支持 form 表單提交。tip
: auto_color line_color 參數僅對小程序碼生效。
/* * 獲取二維碼
* 這裏的 post 方法 爲 json post【重點】 */ @RequestMapping("/getCode") public ResponseMsg getCodeM(HttpServletRequest request) throws Exception { String imei ="867186032552993"; String page="page/msg_waist/msg_waist"; String token = getToken(); // 獲得token Map<String, Object> params = new HashMap<>(); params.put("scene", imei); //參數 params.put("page", "page/msg_waist/msg_waist"); //位置 params.put("width", 430); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token); // 接口 httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); String body = JSON.toJSONString(params); //必須是json模式的 post StringEntity entity; entity = new StringEntity(body); entity.setContentType("image/png"); httpPost.setEntity(entity); HttpResponse response; response = httpClient.execute(httpPost); InputStream inputStream = response.getEntity().getContent(); String name = imei+".png"; saveToImgByInputStream(inputStream,"D:\\",name); //保存圖片 return null; } /* * 獲取 token
* 普通的 get 可獲 token */ public String getToken() { try { Map<String, String> map = new LinkedHashMap<String, String>(); map.put("grant_type", grant_type); map.put("appid", appid); map.put("secret", secret); String rt = HttpUtils.sendGet(TOKEN_URL, map); System.out.println(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) { log.error("# 獲取 token 出錯... e:" + e); e.printStackTrace(); return null; } } /** * 將二進制轉換成文件保存 * @param instreams 二進制流 * @param imgPath 圖片的保存路徑 * @param imgName 圖片的名稱 * @return * 1:保存正常 * 0:保存失敗 */ public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){ 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 { } } return stateInt; }