95463f09eb781efd6b527be1b1516917fb7de23e.svn-base 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package cn.com.goldenwater.dcproj.utils;
  2. import javax.net.ssl.*;
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.FileOutputStream;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.security.cert.CertificateException;
  9. import java.security.cert.X509Certificate;
  10. /**
  11. * @author lhc
  12. * @date 2021/3/8 14:27
  13. */
  14. public class HttpsDownloadUtils {
  15. /**
  16. * @param fileUrl https 远程路径
  17. * @param fileLocal 本地文件存放路径,需要注意的是这里是要传一个已经存在的文件,否则会报拒绝访问的的错误
  18. * @throws Exception
  19. */
  20. public static void downloadFile(String fileUrl, String fileLocal) throws Exception {
  21. SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
  22. sslcontext.init(null, new TrustManager[]{new X509TrustUtiil()}, new java.security.SecureRandom());
  23. URL url = new URL(fileUrl);
  24. HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
  25. @Override
  26. public boolean verify(String s, SSLSession sslsession) {
  27. //log.warn("Hostname is not matched for cert.");
  28. return true;
  29. }
  30. };
  31. HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
  32. HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
  33. HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection();
  34. urlCon.setConnectTimeout(6000);
  35. urlCon.setReadTimeout(6000);
  36. int code = urlCon.getResponseCode();
  37. if (code != HttpURLConnection.HTTP_OK) {
  38. throw new Exception("文件读取失败");
  39. }
  40. // 读文件流
  41. DataInputStream in = new DataInputStream(urlCon.getInputStream());
  42. DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
  43. byte[] buffer = new byte[2048];
  44. int count = 0;
  45. while ((count = in.read(buffer)) > 0) {
  46. out.write(buffer, 0, count);
  47. }
  48. out.close();
  49. in.close();
  50. }
  51. /**
  52. * X509Trust
  53. */
  54. static class X509TrustUtiil implements X509TrustManager {
  55. @Override
  56. public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  57. }
  58. @Override
  59. public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  60. }
  61. @Override
  62. public X509Certificate[] getAcceptedIssuers() {
  63. return null;
  64. }
  65. }
  66. public static void main(String[] args) throws Exception {
  67. downloadFile("https://xxx/xxx.txt", "E:\\test.xls");
  68. }
  69. }