java springboot环境下,处理获取小程序码返回的Buffer数据
发布于 2 年前 作者 wangxiuying 736 次浏览 来自 分享

文档链接:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html

注意请求成功时,只会返回buffer数据
可以用字节数组接收返回数据。当字节数组长度比较小时,判断为请求失败。

/**
     * 获取小程序码 base64编码
     *
     * @param scene 小程序码中的参数
     * @param page  小程序页面
     * @return 小程序码 base64编码数据
     */
    public String getMiniProgramCode(String scene, String page) {
        Object val = redisService.getValue(ACCESS_TOKEN_REDIS_KEY);
        String accessToken = Optional.ofNullable(val).map(String::valueOf).orElse(null);
        if (StringUtils.isBlank(accessToken)) {
            accessToken = getAccessToken();
        }
        HashMap<String, Object> body = new HashMap<>();
        body.put("scene", scene);
        body.put("page", page);
        body.put("env_version", miniProgramConfig.getEnvVersion());
        body.put("width", 114);
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(body, null);
        ResponseEntity<byte[]> entity = restTemplate.exchange(GET_MINI_PROGRAM_CODE_URL + "?access_token=" + accessToken, HttpMethod.POST, httpEntity, byte[].class);
        byte[] buffer = entity.getBody();
        // 成功时微信服务直接返回小程序码的二进制数据,字节数组的长度会很大(大概是60000多)
        if (entity.getStatusCode() != HttpStatus.OK || buffer == null || buffer.length < 200) {
            log.error("请求获取小程序码失败, response: {}", Optional.ofNullable(buffer).map(String::new).orElse("response is null"));
            throw new InternalErrorException(BusinessCode.NOT_IMPLEMENTED);
        }
        return Base64.getEncoder().encodeToString(buffer);
    }
1 回复

可以判断content-type

回到顶部