2012-04-13 26 views
6

Deseo descargar un archivo del servidor que está utilizando el protocolo de conexión segura HTTPS. Podría hacerlo en el servidor normal, pero, cómo puedo hacerlo usando el HTTPS. Si alguien ha usado la API de muestra, ayúdeme a encontrar los recursos útiles.Descargar archivo del servidor HTTPS utilizando Java

+0

Esta [publicación] (http://stackoverflow.com/questions/1828775/httpclient-and-ssl) tiene mucha información útil sobre la negociación de protocolo de enlace SSL y el certificado autofirmado. – MarkOfHall

Respuesta

21

El acceso a una url HTTPS con Java es el mismo y luego se accede a una url HTTP. Siempre se puede utilizar el

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

embargo, puede tener algún problema cuando una cadena de certificados del servidor no puede ser validado. Por lo tanto, es posible que deba deshabilitar la validación de certificados con fines de prueba y confiar en todos los certificados.

Para hacer eso escritura:

// 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

¡Esto funciona genial! Solo para la finalización, Guillaume Polet ha sugerido una forma de proporcionar permisos cuando sea necesario en este hilo http://stackoverflow.com/questions/10479434/server-returned-http-response-code-401-for-url-https. Tuve que agregar esa parte también. –

0

no hay diferencia descargando http vs https. abra una HttpURLConnection a la URL correcta y lea la secuencia resultante.

+0

@hariszhr - ¿Qué es tan gracioso? – jtahlborn

+1

@hariszhr - HttpsURLConnection es una subclase de HttpURLConnection. no es necesario que use específicamente esa clase directamente. Java utilizará la implementación correcta en función del protocolo de la URL. en el futuro, no recomendaría respuestas burlonas sin entender realmente los detalles relevantes. – jtahlborn

0

Debería poder hacerlo exactamente con el mismo código, a menos que el certificado SSL no valide. Esto normalmente sucedería si se tratara de un certificado autofirmado, o si el certificado es de una CA de la que su sistema no tiene conocimiento.

En tal caso, debe manejar la validación del certificado en el código. Solo esa parte de tu código cambiaría. Todo lo demás permanecerá igual.

Primero, pruebe con el mismo código y vea si obtiene una Excepción de certificado.

1

en realidad tenía el mismo problema. No pude descargar archivos del servidor HTTPS. Luego arreglé este problema con esta solución:

// 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(); 
} 

Utilice esta función ... Espero que se beneficie con esta solución fácil.

Cuestiones relacionadas