package com.example.donwloader; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.ArrayList; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.security.cert.X509Certificate; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { public static final int DIALOG_DOWNLOAD_PROGRESS = 0; public static final int DIALOG_EXCEPTION = 1; private Button startBtn; private ProgressDialog mProgressDialog; File rootDir = Environment.getExternalStorageDirectory(); String urlhttps = "https://tibisay.cenditel.gob.ve/trac/raw-attachment/wiki/WikiStart/actados.2.bdoc"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startBtn = (Button)findViewById(R.id.startBtn); startBtn.setOnClickListener(new OnClickListener(){ public void onClick(View v) { startDownload(); } }); } private void startDownload() { //String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"; String url = "https://tibisay.cenditel.gob.ve/trac/raw-attachment/wiki/WikiStart/actados.2.bdoc"; //String url = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG"; checkAndCreateDirectory("/midescarga"); new DownloadFileAsync().execute(url, "false"); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Downloading file.."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(false); mProgressDialog.show(); return mProgressDialog; default: return null; } } class DownloadFileAsync extends AsyncTask> { @Override protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected ArrayList doInBackground(String... params) { int count; Log.d("doInBackground", params[0]); // resultArray [0] -> 0 para ruta de archivo valida // resultArray [0] -> 1 ocurrio un error // resultArray [1] -> ruta del archivo descargado // resultArray [1] -> mensaje de la excepcion ArrayList resultArray = new ArrayList(); try { URL url = new URL(params[0]); int lenghtOfFile = 0; InputStream input = null; if (url.getProtocol().equals("http")){ HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); input = new BufferedInputStream(httpConnection.getInputStream()); lenghtOfFile = httpConnection.getContentLength(); }else{ // https // ejecutar la descarga despues de haber aceptado que el certificado // no es conocido if (params[1].equals("true")){ Log.d("***", "params[1].equals(true)"); // descarga del certificado del servidor CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.cenditel.gob.ve.pem")); //InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.pem")); Certificate ca; try { ca = cf.generateCertificate(caInput); Log.d("", ca.toString()); } finally { caInput.close(); } Log.d("***", "despues de Certificate ca"); // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); Log.d("***", "despues de crear KeyStore"); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); Log.d("***", "despues de crear TrustManager"); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); Log.d("***", "despues de crear SSLContext"); HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); Log.d("***", "despues de crear httpsConnection"); httpsConnection.setSSLSocketFactory(context.getSocketFactory()); Log.d("***", "despues de crear setSSLSocketFactory"); //input = new BufferedInputStream(httpsConnection.getInputStream()); input = httpsConnection.getInputStream(); Log.d("***", "despues de crear BufferedInputStream"); lenghtOfFile = httpsConnection.getContentLength(); Log.d("***", "se acepto la excepcion"); }else{ HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); input = new BufferedInputStream(httpsConnection.getInputStream()); lenghtOfFile = httpsConnection.getContentLength(); } } //int lenghtOfFile = conexion.getContentLength(); Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); //InputStream input = new BufferedInputStream(url.openStream()); //InputStream input = new BufferedInputStream(conexion.getInputStream()); //OutputStream output = new FileOutputStream("/mnt/sdcard/TibisayMovil/ExtractedFiles/photo.jpg"); //OutputStream output = new FileOutputStream(new File(rootDir+"/midescarga/", "foto.jpg")); OutputStream output = new FileOutputStream(new File(rootDir, "acta.2.bdoc")); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; publishProgress(""+(int)((total*100)/lenghtOfFile)); output.write(data, 0, count); } output.flush(); resultArray.add("0"); resultArray.add(output.toString()); output.close(); input.close(); } catch (Exception e) { Log.e("Error: ", e.getMessage()); resultArray.add("1"); resultArray.add(e.toString()); } //return null; return resultArray; } protected void onProgressUpdate(String... progress) { Log.d("ANDRO_ASYNC",progress[0]); mProgressDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected void onPostExecute(ArrayList result) { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); Toast.makeText(getApplicationContext(), "onPostExecute: "+ result.get(0), Toast.LENGTH_LONG).show(); // ocurrio una excepcion if (result.get(0).equals("1")){ // ocurrio un problema AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage(result.get(1)).setTitle("Error al descargar el archivo"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button Log.d("***", "DownloadFileAsync().execute(urlhttps, true)"); Toast.makeText(getApplicationContext(), "DownloadFileAsync().execute(urlhttps, true)", Toast.LENGTH_LONG).show(); // pasar como segundo argmento que se acepta que el sertivor es desconocido new DownloadFileAsync().execute(urlhttps, "true"); } }); builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog dialog = builder.create(); dialog.show(); }else{ } } } //function to verify if directory exists public void checkAndCreateDirectory(String dirName){ File new_dir = new File( rootDir + dirName ); if( !new_dir.exists() ){ Toast.makeText(getApplicationContext(), "checkAndCreateDirectory", Toast.LENGTH_SHORT).show(); if(!new_dir.mkdirs()){ Toast.makeText(getApplicationContext(), "FALLO checkAndCreateDirectory", Toast.LENGTH_SHORT).show(); } } } }