HttpsURLConnection HttpURLConnection下载图片
作者:互联网
package com.sunward.car.util; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; /** * 图片下载 * * @author chong.zuo * @date 2021/5/15 09:18 */ public class downimage { public static void main(String[] args) throws Exception { URL url = new URL("https://ip:port/pic?9dd639268-0do541l*14e622--40ef4798c9152i7b5*=2d6i6s1*=idp4*=pd*m5i1t=1e2264806i8s=*3az899140pi-39o=3cf=9i074&AccessKeyId=pIEGwKgek/eclGpn&Expires=1621129268&Signature=wHmH02mJzQanEoBhL1h94Lr6DhQ="); // openapi.alipay.com FileOutputStream fos = null; HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // 新增部分 conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.connect(); fos = new FileOutputStream("E:\\haha.jpg"); BufferedInputStream bis =new BufferedInputStream(conn.getInputStream()); byte[] data = new byte[2048]; int len = 0; int sum = 0; while ((len = bis.read(data)) != -1) { fos.write(data, 0, len); } fos.flush(); fos.close(); bis.close(); conn.disconnect(); } public void saveToFile(String destUrl) { FileOutputStream fos = null; BufferedInputStream bis = null; HttpURLConnection httpUrl = null; URL url = null; int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int size = 0; try { url = new URL(destUrl); httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); fos = new FileOutputStream("E:\\haha.jpg"); while ((size = bis.read(buf)) != -1) { fos.write(buf, 0, size); } fos.flush(); } catch (IOException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } finally { try { fos.close(); bis.close(); httpUrl.disconnect(); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } } } /* public static void main(String[] args) { downimage dw=new downimage(); dw.saveToFile("https://172.16.9.76:6114/pic?9dd639268-0do541l*44e602--40ef4798c9152i7b5*=3d3i7s1*=idp2*=pd*m3i1t=0e2169883i4s=*3az639142pi-39o=3cf=9i074&AccessKeyId=pIEGwKgek/eclGpn&Expires=1620977838&Signature=bQtjVgUSVrTCJ98PQNODKgSkWvg="); //dw.saveToFile("http://192.168.126.110/group1/M00/00/00/wKh-bmCYpXCAah8aAA5Qo-gsYwM044.png"); }*/ }
public class TrustAnyHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }
标签:fos,URL,httpUrl,public,HttpURLConnection,HttpsURLConnection,new,bis,下载 来源: https://www.cnblogs.com/chong-zuo3322/p/14788603.html