生成二维码保存到本地路径就不说了,论坛很多博主有分享。下面直接上代码
1.接口方法
public class QrCodeController {
public void smallProgramCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
String userId = request.getParameter("userId");
//获取AccessToken
String accessToken = GetWebAccessToken.getAccessToken();
//设置响应类型
response.setContentType("image/png");
String url = WxPayAppletContans.QRCODE_URL.replace("$ACCESS_TOKEN", accessToken);
//组装参数
Map<String, Object> paraMap = new HashMap();
//二维码携带参数 不超过32位 参数类型必须是字符串
paraMap.put("scene", userId);
//二维码跳转页面
paraMap.put("path", "pages/home/home");
//执行post 获取数据流
byte[] result = HttpRequest.doImgPost(url, paraMap);
//输出图片到页面
PrintWriter out = response.getWriter();
InputStream is = new ByteArrayInputStream(result);
int a = is.read();
while (a != -1) {
out.print((char) a);
a = is.read();
}
out.flush();
out.close();
}
}
2.获取accessToken
public class GetWebAccessToken {
/**
* 用户获取生成二维码的access_token
*/
public static String getAccessToken(){
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+"你的小程序appId"+"&secret="+"小程序密钥";
JSONObject jsonObject = HttpRequest.httpRequest(requestUrl, "GET", null);
return jsonObject.getString("access_token");
}
}
3.http工具类
public class HttpRequest{
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
// 设置连接主机服务器的超时时间:15000毫秒
httpUrlConn.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
httpUrlConn.setReadTimeout(60000);
if ("GET".equalsIgnoreCase(requestMethod)) {
httpUrlConn.connect();
}
// 当有数据需要提交时
if (outputStr != null) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 获取数据流
*
* @param url
* @param paraMap
* @return
*/
public static byte[] doImgPost(String url, Map<String, Object> paraMap) {
byte[] result = null;
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
try{
// 设置请求的参数
JSONObject postData = new JSONObject();
for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
postData.put(entry.getKey(), entry.getValue());
}
httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toByteArray(entity);
}catch (ConnectionPoolTimeoutException e){
e.printStackTrace();
}catch (ConnectTimeoutException e){
e.printStackTrace();
}catch (SocketTimeoutException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
httpPost.releaseConnection();
}
return result;
}
}
4.测试
