6.4.3 换取二维码

不管是临时二维码还是永久二维码,创建成功后都会得到二维码ticket,通过ticket可以换取二维码图片。换取二维码的接口地址如下:

  1. https:// mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET

笔者将换取二维码的操作封装成getQRCode()方法,该方法的实现如下:

  1. 1 /**
  2. 2  * 根据ticket换取二维码
  3. 3  *
  4. 4  * @param ticket 二维码ticket
  5. 5  * @param savePath 保存路径
  6. 6  */
  7. 7 public static String getQRCode(String ticket, String savePath) {
  8. 8  String filePath = null;
  9. 9  // 拼接请求地址
  10. 10  String requestUrl = "https:// mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
  11. 11  requestUrl = requestUrl.replace("TICKET", CommonUtil.urlEncodeUTF8(ticket));
  12. 12  try {
  13. 13  URL url = new URL(requestUrl);
  14. 14  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  15. 15  conn.setDoInput(true);
  16. 16  conn.setRequestMethod("GET");
  17. 17 
  18. 18  if (!savePath.endsWith("/")) {
  19. 19  savePath += "/";
  20. 20  }
  21. 21  // 将ticket作为文件名
  22. 22  filePath = savePath + ticket + ".jpg";
  23. 23 
  24. 24  // 将微信服务器返回的输入流写入文件
  25. 25  BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
  26. 26  FileOutputStream fos = new FileOutputStream(new File(filePath));
  27. 27  byte[] buf = new byte[8096];
  28. 28  int size = 0;
  29. 29  while ((size = bis.read(buf)) != -1)
  30. 30  fos.write(buf, 0, size);
  31. 31  fos.close();
  32. 32  bis.close();
  33. 33 
  34. 34  conn.disconnect();
  35. 35  log.info("根据ticket换取二维码成功,filePath=" + filePath);
  36. 36  } catch (Exception e) {
  37. 37  filePath = null;
  38. 38  log.error(“根据ticket换取二维码失败:{}”, e);
  39. 39  }
  40. 40  return filePath;
  41. 41 }

getQRCode()方法的作用是将ticket换取到的二维码存储在路径savePath下。由于ticket中可能会包含加号“+”,而“+”在URL中表示空格,因此必须对ticket进行URL编码。代码中的第11行调用了CommonUtil类的urlEncodeUTF8()方法对ticket进行编码,urlEncodeUTF8()方法的定义如下:

  1. /**
  2. * URL编码(utf-8)
  3. *
  4. * @param source
  5. * @return
  6. */
  7. public static String urlEncodeUTF8(String source) {
  8. String result = source;
  9. try {
  10. result = java.net.URLEncoder.encode(source, "utf-8");
  11. } catch (UnsupportedEncodingException e) {
  12. e.printStackTrace();
  13. }
  14. return result;
  15. }