package org.mp.api.qrcode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class QrcodeDownload {


    //微信二维码下载
    public static void downPicture(HttpServletRequest request, HttpServletResponse response, String ticket, String title) throws IOException {
        ticket="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
        String prefix = "jpg";
//获取文件

        URL url = new URL(ticket);
        URLConnection conn = url.openConnection();
//设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//输出流
        InputStream fs = conn.getInputStream();

        int bytesRead = 0;
        byte[] image = new byte[8192];
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("gb2312"), "ISO8859-1") + "." + prefix);
        try {
            while ((bytesRead = fs.read(image, 0, 8192)) != -1) {
                response.getOutputStream().write(image, 0, bytesRead);

            }
            fs.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
