最近在做小程序水运头条获取获取小程序码时,遇到一个很细微的问题,导致小程序码显示不完整或者干脆不显示的问题.最后找了很久才找到,原因就是调用微信获取小程序码接口返回字节流大小的时候,我是用instreams.available()获取的文件字节大小的.而这个方法在从网络中下载文件时,由于网络是不稳定的,也就是说网络下载时,read()方法是阻塞的,说明这时我们用inputStream.available()获取不到文件的总大小。这时我们需要在请求返回字节时,通过httpconn.getContentLength()获去文件大小,即可得到完整的小程序码.(注意:由于前端显示图片不支持二进制而支持Base64,所以我下面的代码才需要将二进制数据用Base64编码返回的).
官方文档:获取二维码
这里使用其中的接口B:
字段含义写的很清楚,需要注意的是page是小程序中已发布页面,且不能携带参数,参数放在scene中。请求成功的话微信服务器返回的是输入流,需要自行保存,以下看代码:
public static String getShareCode(String sceneStr, String page) { try { String token = getAccessToken(); if (StringUtil.isEmpty(token)) { return null; } String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token; Map<String,Object> param = new HashMap<>(); param.put("scene", sceneStr); param.put("page", page); param.put("width", 430); param.put("auto_color", false); Map<String,Object> line_color = new HashMap<>(); line_color.put("r", 0); line_color.put("g", 0); line_color.put("b", 0); param.put("line_color", line_color); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Param:" + param); } JSONObject json = JSONObject.fromObject(param); String res = httpPostWithJSON(url, json.toString()); return res; } catch (Exception e) { LOGGER.error("Get share code failed!", e); } return null; }
public static String httpPostWithJSON(String url, String json) throws Exception { String result = null; URL target = new URL(url); try { HttpURLConnection httpURLConnection = (HttpURLConnection) target.openConnection(); httpURLConnection.setRequestMethod("GET");// 提交模式 // 发送POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); // 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); printWriter.write(json.toString()); // flush输出流的缓冲 printWriter.flush(); InputStream instreams = httpURLConnection.getInputStream(); byte[] dest = new byte[1024]; byte[] bytes = new byte[httpURLConnection.getContentLength()]; int len; int sum = 0; while ((len = instreams.read(dest)) != -1) { System.arraycopy(dest, 0, bytes, sum, len); if (sum == httpURLConnection.getContentLength()) { break; } else { sum = sum + len; } } // 6. 断开连接,释放资源 httpURLConnection.disconnect(); // 将文件中的内容读入到数组中 result = new BASE64Encoder().encode(bytes); } catch (Exception e) { LOGGER.error(" httpPostWithJSON failed!", e); } return result; }