6.4.3 换取二维码
不管是临时二维码还是永久二维码,创建成功后都会得到二维码ticket,通过ticket可以换取二维码图片。换取二维码的接口地址如下:
- https:// mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
笔者将换取二维码的操作封装成getQRCode()方法,该方法的实现如下:
- 1 /**
- 2 * 根据ticket换取二维码
- 3 *
- 4 * @param ticket 二维码ticket
- 5 * @param savePath 保存路径
- 6 */
- 7 public static String getQRCode(String ticket, String savePath) {
- 8 String filePath = null;
- 9 // 拼接请求地址
- 10 String requestUrl = "https:// mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
- 11 requestUrl = requestUrl.replace("TICKET", CommonUtil.urlEncodeUTF8(ticket));
- 12 try {
- 13 URL url = new URL(requestUrl);
- 14 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
- 15 conn.setDoInput(true);
- 16 conn.setRequestMethod("GET");
- 17
- 18 if (!savePath.endsWith("/")) {
- 19 savePath += "/";
- 20 }
- 21 // 将ticket作为文件名
- 22 filePath = savePath + ticket + ".jpg";
- 23
- 24 // 将微信服务器返回的输入流写入文件
- 25 BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
- 26 FileOutputStream fos = new FileOutputStream(new File(filePath));
- 27 byte[] buf = new byte[8096];
- 28 int size = 0;
- 29 while ((size = bis.read(buf)) != -1)
- 30 fos.write(buf, 0, size);
- 31 fos.close();
- 32 bis.close();
- 33
- 34 conn.disconnect();
- 35 log.info("根据ticket换取二维码成功,filePath=" + filePath);
- 36 } catch (Exception e) {
- 37 filePath = null;
- 38 log.error(“根据ticket换取二维码失败:{}”, e);
- 39 }
- 40 return filePath;
- 41 }
getQRCode()方法的作用是将ticket换取到的二维码存储在路径savePath下。由于ticket中可能会包含加号“+”,而“+”在URL中表示空格,因此必须对ticket进行URL编码。代码中的第11行调用了CommonUtil类的urlEncodeUTF8()方法对ticket进行编码,urlEncodeUTF8()方法的定义如下:
- /**
- * URL编码(utf-8)
- *
- * @param source
- * @return
- */
- public static String urlEncodeUTF8(String source) {
- String result = source;
- try {
- result = java.net.URLEncoder.encode(source, "utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return result;
- }