阅读小程序API
熟读官网API接口
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
主要是看中:通过该接口生成的小程序码,永久有效,数量暂无限制 果断选择
踩坑1:传入参数类型一定得与API一致
注意:参数类型 page 必须是已经发布的小程序存在的页面(否则报错)
/**
* 通过该接口生成的小程序码,永久有效,数量暂无限制
* @param accessToken
* @param scene
* @param pageUrl
* @return
*/
//https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
public static byte[] getWxMiniQrCode(String accessToken, String scene, String pageUrl){
String requestUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
Map<String, Object> requestParam = new HashMap<>();
requestParam.put("scene", scene); //最大32个可见字符,只支持数字,大小写英文以及部分特殊字符
requestParam.put("page", pageUrl); //必须是已经发布的小程序存在的页面(否则报错)
requestParam.put("width", 430); //二维码的宽度,单位 px,最小 280px,最大 1280px 默认 430
requestParam.put("auto_color", false); //自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
// requestParam.put("line_color", ""); //auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
requestParam.put("is_hyaline", true); //是否需要透明底色,为 true 时,生成透明底色的小程序
return UrlUtils.sendPostJson2(requestUrl, JSONObject.toJSONString(requestParam));
}
踩坑2:可以先采用postman去调用一下接口先排除其他因素导致接口调用不成功
/**
* 发送post请求 有参数 json
* @param url
* @param json
* @return
*/
public static byte[] sendPostJson2(String url, String json) {
InputStream inputStream = null;
byte[] data = null;
// 创建默认的CloseableHttpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
try {
StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
s.setContentEncoding("UTF-8");
httppost.setEntity(s);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
// 获取相应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
inputStream = entity.getContent();
data = readInputStream(inputStream);
}
return data;
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
/**
* 将流 保存为数据数组
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 把outStream里的数据写入内存
return outStream.toByteArray();
}
踩坑3: 生成文件并保存在本地
搞定收工!