-
导入依赖
<!-- 工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.13</version>
</dependency>
2.工具类
package com.xiaochi.change.merchant.info.utils;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* @DESCRIPTION:小程序二维码
* @USER: zhengshuang
*/
@Slf4j
public class WeixinQRCodeUtils {
public static String getAccessTokenAsUrl(String appId,String appSecret){
String tokenStr= HttpUtil.get(ConstantUtils.GET_WEIXINTOKEN_URL+"&appid="+appId+"&secret="+appSecret+"");
JSONObject jsonObject = JSONObject.parseObject(tokenStr);
return "?access_token="+jsonObject.getString("access_token");
}
/**
* 下载小程序二维码
*/
public static String downloadMiniCode(String appId, String appSecret, String pathStr,String certNumber) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("scene", certNumber);
paramMap.put("is_hyaline", false);//参数为ture没有底色,false则底色是白色
paramMap.put("width",1280);
String imgFilePath = pathStr + certNumber + ".png";// 新生成的图片
try {
URL url = new URL(ConstantUtils.GET_MINICODE_URL + getAccessTokenAsUrl(appId,appSecret));
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
printWriter.write(JSON.toJSONString(paramMap));
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
OutputStream os = new FileOutputStream(new File(imgFilePath));
// OutputStream os = new FileOutputStream(new File("D:/test/2.png"));
int len;
//设置缓冲写入
byte[] arr = new byte[2048];
while ((len = bis.read(arr)) != -1) {
os.write(arr, 0, len);
os.flush();
}
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return imgFilePath;
}
//本地测试
public static void main(String[] args) {
downloadMiniCode("自己的appId","自己的appSecret","D:/test/","参数");
}
}