12

我想从使用安全连接协议 HTTPS 的服务器下载文件。我可以在普通服务器上做到这一点,但是,我如何使用 HTTPS 做到这一点。如果有人使用过示例 API,请帮助我找到有用的资源。

4

4 回答 4

39

使用 Java 访问 HTTPS url 与访问 HTTP url 相同。您可以随时使用

URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file

但是,当无法验证服务器的证书链时,您可能会遇到一些问题。因此,出于测试目的,您可能需要禁用证书验证并信任所有证书。

要做到这一点,请写:

// Create a new trust manager that trust all certificates
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Activate the new trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// And as before now you can use URL and URLConnection
URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file
于 2012-04-13T04:34:02.663 回答
4

其实我也有类似的问题。我无法从 HTTPS 服务器下载文件。然后我用这个解决方案解决了这个问题:

// But are u denied access?
// well here is the solution.
public static void TheKing_DownloadFileFromURL(String search, String path) throws IOException {

    // This will get input data from the server
    InputStream inputStream = null;

    // This will read the data from the server;
    OutputStream outputStream = null;

    try {
        // This will open a socket from client to server
        URL url = new URL(search);

        // This user agent is for if the server wants real humans to visit
        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

        // This socket type will allow to set user_agent
        URLConnection con = url.openConnection();

        // Setting the user agent
        con.setRequestProperty("User-Agent", USER_AGENT);

        //Getting content Length
        int contentLength = con.getContentLength();
        System.out.println("File contentLength = " + contentLength + " bytes");


        // Requesting input data from server
        inputStream = con.getInputStream();

        // Open local file writer
        outputStream = new FileOutputStream(path);

        // Limiting byte written to file per loop
        byte[] buffer = new byte[2048];

        // Increments file size
        int length;
        int downloaded = 0; 

        // Looping until server finishes
        while ((length = inputStream.read(buffer)) != -1) 
        {
            // Writing data
            outputStream.write(buffer, 0, length);
            downloaded+=length;
            //System.out.println("Downlad Status: " + (downloaded * 100) / (contentLength * 1.0) + "%");


        }
    } catch (Exception ex) {
        //Logger.getLogger(WebCrawler.class.getName()).log(Level.SEVERE, null, ex);
    }

    // closing used resources
    // The computer will not be able to use the image
    // This is a must
    outputStream.close();
    inputStream.close();
}

使用此功能...希望您能从这个简单的解决方案中受益。

于 2017-12-11T20:34:08.330 回答
1

除非 SSL 证书未通过验证,否则您应该能够使用完全相同的代码来执行此操作。如果它是自签名证书,或者证书来自您的系统不知道的 CA,通常会发生这种情况。

在这种情况下,您应该在代码中处理证书验证。只有那部分代码会改变。其他一切都将保持不变。

首先尝试使用相同的代码,看看您是否得到证书异常。

于 2012-04-13T04:21:44.740 回答
0

下载http和https没有区别。打开一个指向正确 URL 的 HttpURLConnection 并读取结果流。

于 2012-04-13T04:21:30.717 回答