微信二维码下载
问题场景:
微信个人二维码要与一张图片合成,二维码是微信用户个人二维码,发现不能合成,原因未知,解决方案是将微信个人二维码下载到本地,再合成,合成代码这里不做演示,只演示个下载的代码
package link; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; /** * Created by Administrator on 2017/7/18 0018. */ public class DownLoadQrCode { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { download("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFH8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyVm1rZ0VkSmVhV1QxMDAwME0wM0wAAgQzCmZZAwQAAAAA", "2222.png","c:\\image\\"); } public static void download(String urlString, String filename,String savePath) throws Exception { InputStream is = null; OutputStream os = null; try { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return true; } }; // 构造URL URL url = new URL(urlString); trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); // 打开连接 URLConnection con = url.openConnection(); //设置请求超时为5s con.setConnectTimeout(5 * 1000); // 输入流 is = con.getInputStream(); // 1K的数据缓冲 byte[] bs = new byte[1024]; // 读取到的数据长度 int len; // 输出的文件流 File sf = new File(savePath); if (!sf.exists()) { sf.mkdirs(); } os = new FileOutputStream(sf.getPath() + File.separator + filename); // 开始读取 while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } }catch (Exception e){ e.printStackTrace(); }finally { if(is!=null){ is.close(); } if(os!=null){ os.flush(); // 完毕,关闭所有链接 os.close(); } } } private static void trustAllHttpsCertificates() throws Exception { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new miTM(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext .getInstance("SSL"); sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc .getSocketFactory()); } static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted( java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted( java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } } }