小程序获取二维码无法查看问题

这篇博客探讨了小程序在线上运行时部分客户遇到的二维码生成问题,主要原因是access_token失效导致图片无法预览。作者指出微信API在错误处理上的不便,并分享了一个通过检查返回头部信息来判断请求是否成功的解决方案。同时,作者希望得到关于access_token同步方法的建议。

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

private static final String WXURL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
public static void postClient(String token){
    Map map = new HashMap();
    Map map1 = new HashMap();
    map1.put("r","255");
    map1.put("g","0");
    map1.put("b","36");
    map.put("scene",user.getPromotionCode());
    map.put("page","pages/index/main");
    map.put("width",430);
    map.put("is_hyaline",false);
    map.put("auto_color",false);
    map.put("line_color",map1);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(WXURL+"?access_token="+token);
    httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json");
    String body = JSON.toJSONString(map);
    StringEntity entity = new StringEntity(body);
    entity.setContentType("image/png");
    httpPost.setEntity(entity);
    CloseableHttpResponse execute = httpClient.execute(httpPost);

    byte[] bytes = EntityUtils.toByteArray(execute.getEntity());
    InputStream in = new ByteArrayInputStream(bytes);

    MultipartFile multipartFile = new MockMultipartFile("s.jpg","s.jpg",
                        "",in);
    String upload = fileService.upload(multipartFile, UP_IMG_URL);
}

此部分代码未请求小程序二维码部分代码,主要问题是在线上运行一段时间后,部分客户二维码生成出现问题

主要原因在于 access_token 失效 导致 图片生成后无法预览

因为 httpclient中 只能获取一次实体信息 感觉二进制转字符串,字符串转二进制麻烦

所以多加上 如下判断 当代码中请求没有错误时 返回头部信息为“img/jpeg”  出现错误时会返回  “application/json; encoding=utf-8” 头部信息 

String entity1 = execute.getEntity().getContentType().getValue();
if(entity1.equals("application/json; encoding=utf-8")){
        //刷新access_token操作 此部分可根据框架逻辑进行修改
        AccessSynUtil.flushAccessToken();
        token=AccessSynUtil.refreshToken();
        execute = postClient(map,token);
    }

微信此处真实坑,无论请求正确或者错误都返回二进制流,所以获取返回信息时会相对来说特别麻烦

如果大家有什么好的 access_token 同步方法的话 麻烦留言一下

小弟代码写的烂 望各位大佬凑活着看看,主要是一个解决思路

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值