2012-04-13 59 views
6

我想從使用安全連接協議HTTPS的服務器下載文件。我可以在普通的服務器上完成它,但是,我可以如何使用HTTPS來完成。如果有人使用了示例API,請幫助我找到有用的資源。使用Java從HTTPS服務器下載文件

+0

這[post](http://stackoverflow.com/questions/1828775/httpclient-and-ssl)有很多關於SSL握手協商和自簽名證書的很好的信息。 – MarkOfHall 2012-04-13 04:29:22

回答

21

用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 
+3

這很好用!只是爲了完成,Guillaume Polet建議了一種在需要時提供權限的方法http://stackoverflow.com/questions/10479434/server-returned-http-response-code-401-for-url-https。我還必須添加該部分。 – 2014-04-23 10:58:36

0

下載http vs https沒有區別。打開一個HttpURLConnection到正確的URL並讀取結果流。

+0

@hariszhr - 有什麼好笑的? – jtahlborn 2016-03-01 14:35:30

+1

@hariszhr - HttpsURLConnection是HttpURLConnection的子類。您不需要直接專門使用該類。 java將使用基於URL協議的正確實現。在未來,如果不真正瞭解相關細節,我不會建議嘲笑答案。 – jtahlborn 2016-03-05 17:46:29

0

您應該可以使用完全相同的代碼來執行此操作,除非SSL證書未通過驗證。如果它是一個自簽名證書,或者證書來自您的系統不知道的CA,則通常會發生這種情況。

在這種情況下,您應該在代碼中處理證書驗證。只有那部分代碼會改變。其他一切將保持不變。

先用相同的代碼嘗試一下,看看是否有證書異常。

1

其實我有類似的問題。我無法從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(); 
} 

使用此功能...希望你會受益於這個簡單的解決方案。