Java生成带参数的小程序二维码以io流的方式直接输出到页面

博客跳过二维码保存本地路径的介绍,直接分享代码,包含接口方法、获取accessToken、http工具类以及测试等内容。
生成二维码保存到本地路径就不说了,论坛很多博主有分享。下面直接上代码
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.测试

在这里插入图片描述

<think>我们正在处理用户关于使用Java生成微信小程序二维码(不带Logo、方形)的请求。根据用户需求,我们需要:1.生成方形二维码(微信小程序二维码默认就是方形)2.不带Logo(即不需要在二维码中间添加任何自定义图标)3.使用Java实现微信官方提供了获取小程序二维码的接口,我们可以通过HTTP请求调用该接口获取二维码图片。接口文档可参考:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html根据文档,我们可以使用接口A:适用于需要的码数量较少的业务场景,通过该接口生成小程序码,永久有效,有数量限制(具体限制请查看文档)。接口地址:POSThttps://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN注意:这个接口返回的是图片的二进制(而不是JSON),所以我们需要将返回的二进制数据保存为图片。步骤:1.获取access_token:需要小程序的appid和appsecret调用接口获取。2.构造请求参数,以JSON格式发送POST请求到上述接口。3.接收返回的二进制数据,写入图片文件。参数说明(部分):-path:扫码进入的小程序页面路径,最大长度128字节,不能为空(例如:"pages/index/index?query=1")-width:二维码的宽度,单位px,默认430px,最小280px,最大1280px(这里我们只需要方形,而微信返回的二维码本身就是方形,所以设置一个值即可,比如430)-auto_color:自动配置线条颜色,如果为true,则不需要传line_color参数-is_hyaline:是否需要透明底色,默认为false(我们不需要透明底色,所以可以不设置,即白色背景)由于我们不需要Logo,所以直接使用接口返回的二维码即可,不需要进行图片合并操作。示例代码(Java):```javaimportjava.io.*;importjava.net.HttpURLConnection;importjava.net.URL;publicclassWxQrCodeGenerator{publicstaticvoidmain(String[]args){//微信小程序的access_token,需要先获取StringaccessToken="YOUR_ACCESS_TOKEN";//替换为你的access_token//请求参数StringrequestBody="{\"path\":\"pages/index/index\",\"width\":430}";try{byte[]qrCode=getWxaCode(accessToken,requestBody);//将二维码图片保存到本地Filefile=newFile("wx_qrcode.png");FileOutputStreamfos=newFileOutputStream(file);fos.write(qrCode);fos.close();System.out.println("二维码生成成功:"+file.getAbsolutePath());}catch(Exceptione){e.printStackTrace();}}publicstaticbyte[]getWxaCode(StringaccessToken,StringrequestBody)throwsIOException{StringurlStr="https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken;URLurl=newURL(urlStr);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setRequestMethod("POST");conn.setDoOutput(true);conn.setRequestProperty("Content-Type","application/json");//发送请求OutputStreamos=conn.getOutputStream();os.write(requestBody.getBytes("UTF-8"));os.close();//获取响应intresponseCode=conn.getResponseCode();if(responseCode!=200){thrownewIOException("HTTPerrorcode:"+responseCode);}//读取返回的二进制数据ByteArrayOutputStreambaos=newByteArrayOutputStream();InputStreamis=conn.getInputStream();byte[]buffer=newbyte[1024];intlen;while((len=is.read(buffer))!=-1){baos.write(buffer,0,len);}baos.close();is.close();returnbaos.toByteArray();}}```注意事项:1.需要先获取access_token,可以通过小程序的appid和appsecret调用`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET`获取(注意有效期,需要缓存)。2.该接口有调用次数限制,具体请参考微信官方文档。3.返回的图片格式为PNG。如果我们需要生成不带任何logo的二维码,那么直接使用这个接口返回的图片即可,因为微信默认返回的二维码中间是没有logo的(只有微信的logo,但这是微信二维码的一部分,不是我们添加的)。用户要求的不带logo,应该是指不在中间添加额外的自定义图标。因此,上述代码已经满足要求:生成方形二维码且不带自定义logo。相关问题:1.如何获取微信小程序的access_token?2.如何将生成二维码图片返回给前端(例如在Web应用中)?3.微信小程序二维码接口的调用限制是怎样的?</think>### 使用Java生成微信小程序二维码(不带Logo/方形)解决方案 微信官方提供了生成小程序二维码的API接口[^1],Java调用程如下: #### 核心步骤 1. **获取Access Token** 需先调用微信API获取访问凭证: $$https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET$$ 2. **调用二维码生成接口** 使用`wxa/getwxacode`接口生成无Logo二维码: $$POST\ https://api.weixin.qq.com/wxa/getwxacode?access_token=TOKEN$$ #### Java实现代码 ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class WxQrCodeGenerator { // 微信配置参数 private static final String APP_ID = "YOUR_APPID"; private static final String APP_SECRET = "YOUR_SECRET"; private static final String QRCODE_PATH = "pages/index/index"; // 小程序页面路径 public static void main(String[] args) { try { // 1. 获取Access Token String accessToken = getAccessToken(); // 2. 生成二维码图片 byte[] qrCode = generateWxaqrCode(accessToken, QRCODE_PATH); // 3. 保存为PNG文件(默认方形无Logo) try (FileOutputStream fos = new FileOutputStream("wx_qrcode.png")) { fos.write(qrCode); } System.out.println("二维码生成成功!"); } catch (IOException e) { e.printStackTrace(); } } // 获取Access Token private static String getAccessToken() throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/token" + "?grant_type=client_credential" + "&appid=" + APP_ID + "&secret=" + APP_SECRET; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); try (BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream()))) { StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } // 解析JSON获取access_token return response.toString().split("\"access_token\":\"")[1].split("\"")[0]; } } // 生成小程序二维码(方形无Logo) private static byte[] generateWxaqrCode(String accessToken, String path) throws IOException { String apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken; // 构造请求参数(默认返回430x430方形二维码) String jsonParams = "{\"path\":\"" + path + "\", \"width\": 430}"; HttpURLConnection conn = (HttpURLConnection) new URL(apiUrl).openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); // 发送请求 try (OutputStream os = conn.getOutputStream()) { byte[] input = jsonParams.getBytes("utf-8"); os.write(input, 0, input.length); } // 获取二进制图片数据 try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = conn.getInputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } return baos.toByteArray(); } } } ``` #### 关键说明 1. **无Logo实现** 微信原生接口返回的二维码**默认不带自定义Logo**,直接使用即可满足需求[^1] 2. **方形保证** 设置`width`参数为相同宽高值(如430)即可保证生成方形二维码 3. **参数说明** - `path`: 小程序页面路径(如`pages/home/index?id=1`) - `width`: 二维码宽度(单位px,范围280-1280) > ⚠️ 注意事项: > 1. 需替换`YOUR_APPID`和`YOUR_SECRET`为实际小程序凭证 > 2. Access Token有效期为2小时,生产环境需缓存复用 > 3. 接口调用频率限制:单个小程序每日100,000次
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值