获取二维码
-
根据业务需要,用户点击分享当前页面,需将小程序当前页面生成二维码,其他用户扫描二维码,跳转至分享页面;
-
官方文档地址
获取二维码 -
请求参数
-
封装请求参数发送请求,请求成功,微信会
返回的图片 Buffer
,需要处理为base64
参数:
createQrCodeUrl:微信官方获取二维码的请求地址;
path:扫码后进入的页面路径。
//发送请求并处理微信返回的Buffer数据
public String getQrCodeImgUrl(String createQrCodeUrl, String path) {
String base64Code = "";
JSONObject createQrParam = new JSONObject();
createQrParam.put("path", path);
PrintWriter out = null;
InputStream in = null;
try {
URL realUrl = new URL(createQrCodeUrl);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数,利用connection的输出流,去写数据到connection中,我的参数数据流出我的电脑内存到connection中,让connection把参数帮我传到URL中去请求。
out.print(createQrParam);
// flush输出流的缓冲
out.flush();
//获取URL的connection中的输入流,这个输入流就是我请求的url返回的数据,返回的数据在这个输入流中,流入我内存,我将从此流中读取数据。
in = conn.getInputStream();
//定义个空字节数组
byte[] data = null;
// 读取图片字节数组
try {
//创建字节数组输出流作为中转仓库,等待被写入数据
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
//向中转的输出流循环写出输入流中的数据
swapStream.write(buff, 0, rc);
}
//此时connection的输入流返回给我们的请求结果数据已经被完全地写入了我们定义的中转输出流swapStream中
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
base64Code = new String(Objects.requireNonNull(Base64.encodeBase64(data)));
//Base64转byte[]数组
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return base64Code;
}
- 最后将生成的base64转换为图片并保存文件
参数:
imgStr:base64字符串;
imgFilePath:图片保存路径。
//将base64转换为图片
public boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}