需求:每个用户生成自己的小程序二维码,前端生成商品海报,用于小程序的推广,废话不多说,看代码
步骤:1 :通过接口获取token,为了避免在冲突,token最好存入redis中,即用即取,注意事项:获取到accessToken取出来是带双引号的,一定要代替掉"",不然返回的转化出来的二进制不对,这个地方坑了我好久,切记切记,还有就是sence这个参数不能带符号,明明官方文档上说的可以带的,但是我带了返回的值就不对,我也不知道为什么 0.0
2:通过接口获取到用户二维码的流,并转化为二进制,这样前台就可以成功读取了
public String getCode(){
String accessToken;
if (redisTemplate.hasKey("token")) {
accessToken = redisTemplate.opsForValue().get("token").toString();
} else {
String token = RestTemplateUtil.get(restTemplate, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(token);
accessToken = jsonObject.get("access_token").toString();
redisTemplate.opsForValue().set("token", accessToken, 1, TimeUnit.HOURS);
}
accessToken = accessToken.replaceAll("\"","");
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
String reslut = SendPost.sendPost3(url,sence);
}
public static String sendPost3(String url,String sence) {
PrintWriter out = null;
String result = "";
InputStream inputStream=null;
//请求数据,自行拼接
String param="{ \"scene\":"+sence+",\"page\":\"pages/user/user\",\"width\":280}";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("responseType", "arraybuffer");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
//获取流数据
inputStream = conn.getInputStream();
// 将获取流转为base64格式
byte[] data = null;
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inputStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
result = new String(Base64.getEncoder().encode(data));
}catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(inputStream!=null){
inputStream.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return "data:image/PNG;base64,"+result;
}