1、通过java网络处理包(java.net)相关方法获取pdf输入流;
2、从输入流中获取字节数组;
3、将输出流写入指定的文件夹;
4、关闭网络获取的输入流;
所谓工欲善其事必先利其器,我们先需要准备:
SslUtils工具类:这个工具类很重要,主要是为了让服务器忽略证书信任问题,如果不使用此工具类则会出现服务器不信任我们自己创建的证书,抛出SSLHandshakeException;
package com.sunfreeter;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SslUtils {
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager, X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
/**
* 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
*
* @throws Exception
*/
public static void ignoreSsl() throws Exception {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}
IoCommonUtil:主要是处理流文件的读写
package com.sunfreeter.thread;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class IoCommonUtil {
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 写入文件
* @param savePath
* @param fileName
* @param getData
* @throws IOException
*/
public static void writeOutputStream(String savePath,String fileName,byte[] getData) throws IOException {
//文件保存位置
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
}
}
工具类有了,我们就可以开始了~~
步骤1:通过java网络处理包(java.net)相关方法获取pdf输入流;
URL url = new URL(urlStr);
SslUtils.ignoreSsl();
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
步骤2:从输入流中获取字节数组;
//获取字节数组
byte[] getData = IoCommonUtil.readInputStream(inputStream);
步骤3:将输出流写入指定的文件夹;
IoCommonUtil.writeOutputStream(savePath, fileName, getData);
步骤4:关闭网络获取的输入流;
if(inputStream!=null){
inputStream.close();
}
最后再附上一个以上四步骤+测试的完整代码,您只需复制粘贴即可(请叫我雷锋族长,吼吼):
package com.sunfreeter.thread;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileManagerSystem {
public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws Exception {
URL url = new URL(urlStr);
SslUtils.ignoreSsl();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(5 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 得到输入流
InputStream inputStream = conn.getInputStream();
// 获取字节数组
byte[] getData = IoCommonUtil.readInputStream(inputStream);
IoCommonUtil.writeOutputStream(savePath, fileName, getData);
if (inputStream != null) {
inputStream.close();
}
System.out.println("info:" + url + " download success");
}
public static void main(String[] args) throws Exception {
String fileUrl = "https://www.debian.org/releases/stable/amd64/install.pdf.zh-cn";
FileManagerSystem.downLoadByUrl(fileUrl, "test.pdf", "F:\迅雷下载");
}
}