java 生成小程序带参数二维码

package com.cn.common;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.cn.common.weChat.WeChatSendMessageUtil;

import net.sf.json.JSONObject;
import sun.util.logging.resources.logging;

/**
 * 小程序二维码带参数生成
 *
 */
public class AppletsQrCodeUtil {
	
	private static Logger log = Logger.getLogger(AppletsQrCodeUtil.class);
	
	/**
	 * 用于获取access_token
	 * @param params
	 * @param APIKEY 小程序id
	 * @param SECRETKEY	小程序密钥
	 * @return  access_token
	 * @throws Exception
	 */
	public static String postToken() throws Exception {
		String APIKEY = "";//小程序id
		String SECRETKEY = "";//小程序密钥
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APIKEY+"&secret="+SECRETKEY;
		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 = null;
		if (requestUrl.contains("nlp"))
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
		else
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
		String accesstoken=jsonObject.getString("access_token");
		return accesstoken;
	}

	/**
	 * 生成带参小程序二维码
	 * @param sceneStr 参数
	 * @param accessToken token
	 * @param fileDir 存放目录
	 * @param fileName 文件名称(不含后缀)
	 * @param format  二维码图片格式,jpg/png
	 */
	private static void getminiqrQr(String sceneStr, String accessToken, String fileDir, String fileName, String format) {
		try
		{
			String url = ("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);

			// 发送请求参数
			JSONObject paramJson = new JSONObject();
			paramJson.put("scene", sceneStr);
			paramJson.put("page", "pages/index/index"); // 这里特别注意前面不要加 '/'
			paramJson.put("width", 430);
			paramJson.put("auto_color", true); // 自动配置线条颜色
			paramJson.put("is_hyaline", true); // 背景色透明
			/**
			 * line_color生效
			 * paramJson.put("auto_color", false);
			 * JSONObject lineColor = new JSONObject();
			 * lineColor.put("r", 0);
			 * lineColor.put("g", 0);
			 * lineColor.put("b", 0);
			 * paramJson.put("line_color", lineColor);
			 * */

		    InputStream is = getQRCodeInputStream(url, paramJson.toString());
		    
		    File file = getFileByInputStream(is, fileDir, fileName + "." + format);
		    file.createNewFile();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private static InputStream getQRCodeInputStream(String strURL, String params) {
	    try {
	        URL url = new URL(strURL);// 创建连接
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setUseCaches(false);
	        connection.setInstanceFollowRedirects(true);
	        connection.setRequestMethod("POST"); // 设置请求方式
	        connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
	        connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
			connection.setRequestProperty("Connection", "Keep-Alive");
	        connection.connect();
	        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
	        out.append(params);
	        out.flush();
	        out.close();
	        InputStream is = connection.getInputStream();
	        return is;

	    } catch (IOException e) {
		    return null;
	    }
	}
	
	private static File getFileByInputStream(InputStream is, String filePath, String fileName) {

		// 构造文件目录,若目录不存在,则创建目录
		if (!new File(filePath).exists()) {
			new File(filePath).mkdirs();
		}
		
		System.out.println(filePath);
		System.out.println(fileName);
		
	    File file=null;
	    if(is!= null&& !org.apache.commons.lang.StringUtils.isEmpty(filePath)&&!org.apache.commons.lang.StringUtils.isEmpty(fileName)){
	        try {
	            file=new File(filePath,fileName);//可以是任何图片格式.jpg,.png等
	            FileOutputStream fos=new FileOutputStream(file);
	            byte[] b = new byte[1024];
	            int nRead = 0;
	            while ((nRead = is.read(b)) != -1) {
	                fos.write(b, 0, nRead);
	            }
	            fos.flush();
	            fos.close();
	        } catch (IOException e) {
	        }
	    }
	    return file;
	}

	
	public static void main(String[] args) throws Exception {
		String accesstoken = postToken();
		System.out.println("accesstoken="+accesstoken);
		getminiqrQr("1", accesstoken, "D:\\", "小程序二维码", "jpg");
		
		// 注意:小程序必须正式发布且页面路径存在才可以生成
		// 如果保存文件为 1kb 时说明失败了,使用编码工具打开看里面的json错误信息对应去微信文档查看解决
	}
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java生成参数小程序二维码,可以使用第三方库或者API来实现。以下是一种可能的方法: 首先,你需要选择一个适合的二维码生成库。在这里,我们以Zxing库为例进行说明。你可以在Maven中添加对Zxing库的依赖,然后在Java项目中使用它。 接下来,你需要创建一个字符串,以包含参数小程序链接。例如,你可以将参数附加到小程序链接的末尾,如下所示:https://xxx.xxx.xxx?param1=xxx&param2=xxx。请根据你的具体需求自行替换链接和参数。 然后,你可以使用Zxing库生成参数小程序二维码。以下是一个代码示例: ```java import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class QrCodeGenerator { public static void main(String[] args) { String content = "https://xxx.xxx.xxx?param1=xxx&param2=xxx"; // 替换为你的参数小程序链接 int width = 300; int height = 300; try { BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height); BufferedImage qrCodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { qrCodeImage.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB()); } } File outputFile = new File("qr_code.jpg"); // 保存二维码的文件名和路径 ImageIO.write(qrCodeImage, "jpg", outputFile); } catch (WriterException | IOException e) { e.printStackTrace(); } } } ``` 运行上述代码后,它将生成一个名为"qr_code.jpg"的图像文件,其中包含参数小程序二维码。 当然,以上只是一种实现方法,你也可以使用其他类库或API来生成参数小程序二维码。希望能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值