@Override public ModelAndView onSubmit(HttpServletRequest req, HttpServletResponse res, WxQrCodeForm cmd, BindException err) throws Exception { SimpleResult<Object> result = SimpleResult.create(false); Locale locale = new Locale("en", "US"); ResourceBundle resource = ResourceBundle.getBundle("config/wx-config", locale); //读取属性文件 String appId = resource.getString("appId"); //开发者设置中的appId String secret = resource.getString("appSecret"); //开发者设置中的appSecret AccessToken accessToken = null; 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(); getminiqrQr(token); return ModelAndViewUtil.json(result); } public Map getminiqrQr(String accessToken) { RestTemplate rest = new RestTemplate(); InputStream inputStream = null; OutputStream outputStream = null; try { String url = "https://api.weixin.qq.com/weixin/getwxacode?access_token=" + accessToken; Map<String, Object> param = new HashMap<>(); param.put("path", "pages/search/search"); //跳转到查询物流(自定义) 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("/Users/apple/Desktop/abc.png"); 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; }
原文地址:https://www.cnblogs.com/dreammyone/p/10711024.html
时间: 2024-10-07 21:46:36