java微信小程序 获取二维码

本文介绍了一种使用Apache HttpClient替代Spring的RestTemplate来获取并保存微信小程序码的方法。通过获取access_token,构造请求参数并发送HTTP POST请求,最终将返回的小程序码保存到本地。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果用Spring那套RestTemplate不能获取,或者获取了生成的图片文件是无法打开的,大小是150多k的(当宽度为430的时候,应该是55k左右),可以看看我的方法


package com.wx.scooter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wx.scooter.tool.CheckTool;
import com.wx.scooter.tool.Constant;
import com.wx.scooter.tool.HttpTool;

public class TestQR {
    public static void main(String[] args) throws Exception {
        //获取token
        String result1 = HttpTool.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+Constant.NATIVE_APP_ID+"&secret="+Constant.NATIVE_APP_SECRET);
        String access_token = JSONObject.parseObject(result1).getString("access_token");
        if(CheckTool.isString(access_token)) {
            System.out.println("token为");
            System.out.println(access_token);
            Map<String, Object> params = new HashMap<>();
            params.put("scene", "test");
            params.put("page", "pages/index/index");
            params.put("width", 430);

            CloseableHttpClient  httpClient = HttpClientBuilder.create().build();

            HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            String body = JSON.toJSONString(params);
            StringEntity entity;
            entity = new StringEntity(body);
            entity.setContentType("image/png");

            httpPost.setEntity(entity);
            HttpResponse response;

            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();

            File targetFile = new File("D:\\");  
            if(!targetFile.exists()){    
                targetFile.mkdirs();    
            }       
            FileOutputStream out = new FileOutputStream("D:\\upload\\5.png");

            byte[] buffer = new byte[8192];
            int bytesRead = 0;
            while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            out.flush();
            out.close();
        } else {
            System.out.println("获取access_token错误");
        }
    }
}

### Java 实现微信小程序生成二维码 #### 准备工作 为了通过Java环境为微信小程序生成二维码,需先完成准备工作。这包括注册并认证微信公众平台账号,创建小程序项目,并获得AppID和AppSecret。 #### 获取AccessToken 获取`accessToken`是调用微信接口的前提条件之一。此令牌用于验证开发者身份以及授权访问特定API资源。可以通过HTTP GET请求来取得该令牌[^2]: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class AccessTokenUtil { private static final String APP_ID = "your_app_id"; private static final String APP_SECRET = "your_app_secret"; public static String getAccessToken() throws Exception { URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 假设返回JSON格式 {"access_token":"ACCESS_TOKEN","expires_in":7200} return parseJson(response.toString(), "access_token"); } private static String parseJson(String json, String key){ int start = json.indexOf("\""+key+"\":\"") + ("\""+key+"\":\"").length(); int end = json.indexOf("\",\"",start); if(end == -1){ end = json.length()-1; } return json.substring(start,end); } } ``` #### 创建无限数量的小程序码 一旦获得了有效的`accessToken`,就可以继续向指定URL发送POST请求以创建带有参数的小程序码。这里需要注意的是,在构建请求体时要遵循微信官方文档中的规定[^1]。 ```java import com.google.gson.Gson; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; class WxaCodeUnlimitRequest { private String scene; // 场景值ID,最多32个可见字符 private String page; // 所需要跳转至页面路径(可带参) } // 使用示例方法 public void createWxacodeUnlimited(){ try(CloseableHttpClient httpClient = HttpClients.createDefault()){ HttpPost post = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+getAccessToken()); WxaCodeUnlimitRequest requestObj = new WxaCodeUnlimitRequest(); requestObj.scene = "test_scene_value"; requestObj.page = "pages/index/index"; Gson gson = new Gson(); String jsonString = gson.toJson(requestObj); StringEntity entity = new StringEntity(jsonString,"UTF-8"); post.setEntity(entity); post.setHeader("Content-Type", "application/json"); try(CloseableHttpResponse response = httpClient.execute(post)){ byte[] bytes = EntityUtils.toByteArray(response.getEntity()); // 将bytes保存成文件或其他处理方式... } catch(Exception e){ System.out.println(e.getMessage()); } }catch(Exception ex){ System.out.println(ex.getMessage()); } } ``` 上述代码展示了如何在Java应用程序中集成微信开放平台提供的服务,从而实现在服务器端动态生成具有自定义场景信息的小程序二维码功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值