String dtoImgUrl = "http://pic.dmjnb.com/pic/67eeb32cdd4800149d26594e587d7696";
String urlName = "D:/downloadResult/files/" + "图片"; //如果文件重名会被覆盖
dataReportUtil.downloadHttpsFile(dtoImgUrl,urlName); //把文件下载到本地
/**
* 通过URL地址下载文件到本地
*
* @param
* @param fileUrl 文件url
* @param fileLocal 保存到本地的地址
* @return
*/
public void downloadHttpsFile(String fileUrl, String fileLocal) throws Exception {
SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
sslcontext.init(null, new TrustManager[]{new X509TrustUtiil()}, new java.security.SecureRandom());
URL url = new URL(fileUrl);
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslsession) {
return true;
}
};
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//连接主机的超时时间
httpConn.setConnectTimeout(6000);
//从主机读取数据的超时时间
httpConn.setReadTimeout(6000);
int code = httpConn.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
// 读文件流
DataInputStream in = new DataInputStream(httpConn.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
byte[] buffer = new byte[2048];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
}
private class X509TrustUtiil implements TrustManager {
}
JAVA通过HTTP将URL地址文件/图片保存到本地文件夹
最新推荐文章于 2024-08-26 23:00:00 发布