小程序獲取二維碼無法查看問題

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” 頭部信息 

if(entity1.equals("application/json; encoding=utf-8")){
        //刷新access_token操作 此部分可根據框架邏輯進行修改
        AccessSynUtil.flushAccessToken();
        token=AccessSynUtil.refreshToken();
        execute = postClient(map,token);
    }

微信此處真實坑,無論請求正確或者錯誤都返回二進制流,所以獲取返回信息時會相對來說特別麻煩

如果大家有什麼好的 access_token 同步方法的話 麻煩留言一下

小弟代碼寫的爛 望各位大佬湊活着看看,主要是一個解決思路

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章