java获取微信小程序二维码保存到本地并返回图片,下次如果检查到本地有图片,那么就返回本地的图片,不再发起请求,否则重新发起请求并保存到本地,直接看代码吧。
获取access_token的方法可以参考:https://blog.csdn.net/qq_26365837/article/details/89969237
private final static String FILE_NAME = "/var/opt/miniProgramImages/%s.png";
/**
* 获取微信的二维码, 适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制
* @param scene 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)
* @param width 二维码的宽度,单位 px,最小 280px,最大 1280px
* @param page 例如 pages/index/index, 根路径前不要填加 /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面
* @param response
* @return void
* @author tyg
* @date 2020年2月9日下午6:27:43
*/
@RequestMapping(value = "/wechat/getMiniQrCode", method = RequestMethod.GET)
public void getWechatCodelimits(String scene, Integer width, String page, HttpServletResponse response) {
// 获取存在文件输入流
InputStream inputStream = null;
// 获取存在文件
File file = getFile(scene+width);
if(!file.exists()){
JSONObject jsonObject = new JSONObject();
jsonObject.put("scene", scene);
jsonObject.put("width", width == null ? 430 : width);
if(StringUtils.isNotBlank(page)) {
jsonObject.put("page", page);
}
System.out.println("\n\n===========获取微信二维码传值大量业务场景,暂无数量限制:" + jsonObject.toJSONString());
inputStream = HttpUtil.sendPostBackStream(WechatConfig.GIVE_MINI_PROGRAM_MORE+wechatI.getAccessToken(), jsonObject.toJSONString());
}
// 响应数据
responseMessage(inputStream, scene+width, file);
}
/**
* 获取文件输入流,文件存在才有,没有文件就没有值
* @param name
* @return
* @return InputStream
* @author tyg
* @date 2020年2月10日上午1:19:16
*/
private File getFile(String name) {
return new File(String.format(FILE_NAME, name));
}
/**
* 响应二维码
* @param inputStream
* @return void
* @author tyg
* @date 2020年2月9日下午9:59:01
*/
private boolean responseMessage(InputStream inputStream, String name, File file) {
ServletOutputStream outputStream = null;
BufferedInputStream inputBuf = null;
response.setContentType("image/png");
try {
if(!file.exists()) {
BufferedImage bi = ImageIO.read(inputStream);
ImageIO.write(bi, "PNG", response.getOutputStream());
ImageIO.write(bi, "PNG", new FileOutputStream(new File(String.format(FILE_NAME, name))));
} else {
byte[] b = new byte[1024];
outputStream = response.getOutputStream();
//使用输入读取缓冲流读取一个文件输入流
inputBuf = new BufferedInputStream(new FileInputStream(file));
while(inputBuf.read(b) != -1){
outputStream.write(b);
}
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
IOUtils.closeQuietly(outputStream);
IOUtils.closeQuietly(inputBuf);
IOUtils.closeQuietly(inputStream);
}
return true;
}