12

保護された接続プロトコルHTTPSを使用しているサーバーからファイルをダウンロードしたい。通常のサーバーで実行できますが、HTTPSを使用して実行するにはどうすればよいですか。誰かがサンプルAPIを使用したことがある場合は、役立つリソースを見つけるのを手伝ってください。

4

4 に答える 4

39

JavaでHTTPSURLにアクセスするのと同じで、HTTPURLにアクセスします。いつでも使用できます

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 に答える