java获取微信二维码进行下载或返回给前端显示
- 1、调用微信接口生成二维码工具类
- 2、设置接收微信二维码
- 3、前端拿到base64显示在页面中
1、调用微信接口生成二维码工具类
com.alibaba
fastjson
1.2.32
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Objects;
public class WxCodeUtil {
public String postToken(String appId, String appsecret) throws Exception {
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appsecret;
URL url = new URL(requestUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("");
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in;
if (requestUrl.contains("nlp"))
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
else
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String getLine;
while ((getLine = in.readLine()) != null) {
result.append(getLine);
}
in.close();
JSONObject jsonObject = JSONObject.parseObject(result.toString());
return jsonObject.getString("access_token");
}
public Object getQrCodeImgUrl(String scene,int width,String page,String token) {
//然后调用微信官方api生成二维码
String createQrCodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token;
//此处我是使用的阿里巴巴的fastJson
JSONObject createQrParam = new JSONObject();
// 设置二维码内容传入的参数
// a=1&b=2
createQrParam.put("scene", scene);
// 这是设置扫描二维码后跳转的页面
// 注意该接口传入的是page而不是path
// 小程序页面地址比如
// page/index/index
createQrParam.put("page", page);
// 设置二维码的宽度,最低280,最大1280
createQrParam.put("width", width);
// 正式版为 release,体验版为 trial,开发版为 develop
createQrParam.put("env_version","trial");
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();
}
}
}
String base64Code = new String(Objects.requireNonNull(Base64.encodeBase64(data)));
//Base64转byte[]数组
System.out.println("方法输出开始--");
System.out.println(base64Code);
System.out.println("方法输出结束--");
return base64Code;
} 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 "";
}
// base64转成图片
public BufferedImage convertBase64ToImage(String base64Code){
BufferedImage image = null;
byte[] imageByte = null;
try {
imageByte = DatatypeConverter.parseBase64Binary(base64Code);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(new ByteArrayInputStream(imageByte));
bis.close();
return imgage;
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、设置接收微信二维码
public class Text{
@Resource
private WxCodeUtil wxcode;
private static final String appid="";
private static final String appsercet="";
// 获取二维码返回下载流
public void exportCode(HttpServletResponse response){
// 1、获取token
String token = wxcode.postToken(appid,appsercet);
int width = 300;//二维码宽
// 2、获取微信二维码的base64编码格式
String baseCode = wxcode.getQrCodeImgUrl("扫描二维码携带的参数",width,"小程序页面",token).toString();
// 3、将base64转换为图片
BufferedImage code = wxcode.convertBase64ToImage(baseCode);
// 4、返回下载流
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=wxcode.jpg");
OutputStream outputStream = response.getOutputStream();
ImageIO.write(code, "jpg", outputStream);
outputStream.flush();
outputStream.close();
}
// 获取二维码返回前端base64
public String wxCodeBase64(HttpServletResponse response){
// 1、获取token
String token = wxcode.postToken(appid,appsercet);
int width = 300;//二维码宽
// 2、获取微信二维码的base64编码格式
String baseCode = wxcode.getQrCodeImgUrl("扫描二维码携带的参数",width,"小程序页面",token).toString();
return baseCode;
}
}
3、前端拿到base64显示在页面中