Java生成临时微信公众号二维码(携带参数)

    /**
     * 生成临时公众号二维码
     * @param params
     * @return 二维码的base64
     * @throws IOException
     */
    public static String getQrCodeImage(String params) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("expire_seconds", 2592000);
            jsonObject.put("action_name", "QR_STR_SCENE");
            JSONObject scene = new JSONObject();
            scene.put("scene_str", params);
            JSONObject actionInfo = new JSONObject();
            actionInfo.put("scene", scene);
            jsonObject.put("action_info", actionInfo);
            String result = doJsonPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + getAccessToken(), jsonObject.toJSONString(), null);
            System.out.println("获取公众号二维码结果:" + result);
            JSONObject object = JSONObject.parseObject(result);
            String ticket = object.getString("ticket");
            BufferedImage bufferedImage = getImage("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket);
            return bufferImageToBase64(builderQrCodeImage(bufferedImage));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 二维码设置自定义的边框
     * @param image
     * @return
     */
    public static BufferedImage builderQrCodeImage(BufferedImage image) {
        try {
            File file = new File("边框图片文件路径");
            BufferedImage borderImage = ImageIO.read(new File(file.getPath()));
            BufferedImage weiXinImage = new BufferedImage(image.getWidth() + 100, image.getHeight() + 100, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = weiXinImage.createGraphics();
            //消除文字锯齿
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            //消除图片锯齿
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //放入二维码
            graphics.drawImage(image, 50, 50, image.getWidth(), image.getHeight(), null);
            //放入边框
            graphics.drawImage(borderImage, 0, 0, image.getWidth() + 100, image.getHeight() + 100, null);
            return weiXinImage;
        } catch (IOException e) {
            return image;
        }
    }

    /**
     * 将BufferedImage转为base64
     * @param bufferedImage
     * @return
     * @throws IOException
     */
	public static String bufferImageToBase64(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", stream);
        // 对字节数组Base64编码
        Base64 base = new Base64();
        String base64 = base.encodeToString(stream.toByteArray());
        return "data:image/png;base64," + base64;
    }

	/**
     * 获取accessToken
     * @return
     */
    private static String getAccessTokens() throws Exception {
        String url ="https://api.weixin.qq.com/cgi-bin/stable_token";
        JSONObject param = new JSONObject();
        param.put("grant_type", "client_credential");
        param.put("appid", "你的AppId");
        param.put("secret", "你的Secret");
        param.put("force_refresh", false);
        String result = doJsonPost(url, param.toJSONString(), null);
        System.out.println("获取AccessToken结果:" + result);
        JSONObject object = JSONObject.parseObject(result);
        return object.getString("access_token");
    }

	/**
	 * 下载网络图片
	 * @param imageUrl
	 * @return
	 */
	public static BufferedImage getImage(String imageUrl) {
		try {
			URL url = new URL(imageUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//设置超时间为240秒
			conn.setConnectTimeout(240 * 1000);
			//防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			//得到输入流
			InputStream inputStream = conn.getInputStream();
			//获取自己数组
			byte[] getData = readInputStream(inputStream);
			BufferedImage image = ImageIO.read(new ByteArrayInputStream(getData));
			return image;
		}catch(Exception e) {
			return null;
		}
	}

	private static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}


	/**
	 * JsonPost请求
	 * @Description: TODO
	 * @param @param postUrl
	 * @param @param param
	 * @param @return
	 * @return String
	 * @throws IOException
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年6月19日
	 */
	public static String doJsonPost(String postUrl, String jsonData, Map<String, Object> property) throws Exception {
		// 封装发送的请求参数
		URL url = new URL(postUrl);
		URLConnection urlConnection = url.openConnection();
		HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
		httpUrlConnection.setConnectTimeout(TIMEOUT);
		httpUrlConnection.setUseCaches(false);//设置不要缓存
		httpUrlConnection.setRequestMethod("POST");
		// 设置请求头属性参数
		httpUrlConnection.setRequestProperty("charset", "UTF-8");
		httpUrlConnection.setRequestProperty("Content-Type","application/json");
		httpUrlConnection.setRequestProperty("connection", "Keep-Alive");
		httpUrlConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		httpUrlConnection.setRequestProperty("accept", "*/*");
		if(property != null) {
			for (Entry<String, Object> map : property.entrySet()) {
				httpUrlConnection.setRequestProperty(map.getKey(), map.getValue().toString());
			}
		}
		// 发送POST请求必须设置如下两行
		httpUrlConnection.setDoOutput(true);
		httpUrlConnection.setDoInput(true);
		String response = "";// 响应内容
		String status = "";// 响应状态
		OutputStream out = null;
		BufferedReader in = null;
		try{
			// 获取URLConnection对象对应的输出流
			out = httpUrlConnection.getOutputStream();
			// 发送Json请求参数
			out.write(jsonData.getBytes());
			// flush输出流的缓冲
			out.flush();
			httpUrlConnection.connect();
			// 定义BufferedReader输入流来读取URL的响应数据
			in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				response += line;
			}
			// 获得URL的响应状态码
			status = new Integer(httpUrlConnection.getResponseCode()).toString();
		}catch(Exception e) {
			e.printStackTrace();
			throw e;
		}finally {
			try {
				if (out != null) { out.close();}
				if (in != null) {in.close();}
			} catch (Exception ex) {
				ex.printStackTrace();
				throw ex;
			}
		}
		if(!status.startsWith("2")) {
			throw new Exception("请求结果错误");
		}
		return response;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值