小程序二维码生成 踩过的坑

微信小程序二维码

前些天在做微信小程序二维码的生成,前面生成token就不说了,主要是生成二维码的接口,腾讯服务器返回的图片的二进制数据,用的另一个工具IOUtils,超轻松的,byte[] data = IOUtils.toByteArray(inputStream);就这样直接把输入流转换成字节组,写到本地文件里,格式为.png,就可以了,IOUtils这个工具在commons-io-2.5.jar这个包里面

代码如下:


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

@WebServlet(name="GetWXCode", urlPatterns={"/getwxcode"})
public class GetWXCode extends HttpServlet
{
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    PrintWriter out = response.getWriter();
    String Token = "";
    String appid = "小程序APPID";
    String secrect = "小程序秘钥";
    JSONObject json = null;
    String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + 
      "&secret=" + secrect;

    String getWxCodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
    String mac = request.getParameter("mac") == null ? null : request.getParameter("mac").toString();

    if (mac == null) {
      out.println("<rep><code>1</code><msg>Missing parameters</msg></rep>");
      return;
    }
    String path = " 缓存图片路径/img/" + mac + ".png";
    File imgFile = new File(path);

    if (imgFile.exists()) {
      out.println("<!DOCTYPE html><html><head></head><body><img src=\"/img/" + mac + 
        ".png" + "\" ></img>" + "</body>" + "</html>");
      return;
    }

    ServletContext servletContext = getServletContext();

    Token = servletContext.getAttribute("Token") == null ? null : servletContext.getAttribute("Token").toString();
    long time = servletContext.getAttribute("token_time") == null ? 0L : ((Long)servletContext.getAttribute("token_time")).longValue();
    long curTime = System.currentTimeMillis();

    if ((Token == null) || (time == 0L) || (curTime - time > 6800000L))
    {
      json = HttpsUtils.httpsRequest(tokenUrl, "GET", null);
      Token = json.get("access_token").toString();

      servletContext.setAttribute("Token", Token);
      servletContext.setAttribute("token_time", Long.valueOf(curTime));
    }

    try
    {
      if (Token != null)
      {
        getWxCodeUrl = getWxCodeUrl + Token;
        JSONObject dataJson = new JSONObject();
        dataJson.put("scene", mac);
        dataJson.put("page", "pages/main2/main2");
        byte[] rep = HttpXmlUtils.httpsRequestStream(getWxCodeUrl, "POST", dataJson.toString());

        imgFile.createNewFile();
        FileOutputStream outputStream = new FileOutputStream(imgFile);
        outputStream.write(rep);
        outputStream.flush();
        outputStream.close();

        out.println("<!DOCTYPE html><html><head></head><body><img src=\"/img/" + 
          mac + ".png" + "\" ></img>" + "</body>" + "</html>");
      }
    }
    catch (Exception e) {
      response.getWriter().append(e.toString());
    }
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    doGet(request, response);
  }
}


import java.io.BufferedReader; 
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.io.IOUtils;


/**
 * post提交xml格式的参数
 *  
 */
public class HttpXmlUtils {
 
	/**
	 * post请求并得到返回结果
	 * @param requestUrl
	 * @param requestMethod
	 * @param output
	 * @return
	 */
	public static byte[] httpsRequestStream(String requestUrl, String requestMethod, String output) {
		try{
			URL url = new URL(requestUrl);
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(requestMethod);
			if (null != output) {
				OutputStream outputStream = connection.getOutputStream();
				outputStream.write(output.getBytes("UTF-8"));
				outputStream.close();
			}
			// 从输入流读取返回内容
			InputStream inputStream = connection.getInputStream();
			
			byte[] data = IOUtils.toByteArray(inputStream);
		 
			inputStream.close();
			inputStream = null;
			connection.disconnect();
			return data;
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return null;
	} 
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灵神翁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值