source: dispositivos_moviles/Donwloader/src/com/example/donwloader/MainActivity.java @ 2ff9cec

Last change on this file since 2ff9cec was 9572f49, checked in by Antonio Araujo Brett <aaraujo@…>, 11 years ago

*- Estudio de API de Android y prueba de concepto para descargar archivos desde una URL con protocolo https y lanzar la Actividad de leer y verificar firma de un contenedor BDOC de la aplicación Tibisay Móvil.

  • Property mode set to 100644
File size: 11.0 KB
Line 
1package com.example.donwloader;
2
3import java.io.BufferedInputStream;
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.FileOutputStream;
7import java.io.InputStream;
8import java.io.OutputStream;
9import java.net.HttpURLConnection;
10import java.net.URL;
11import java.net.URLConnection;
12
13import java.security.KeyStore;
14import java.security.cert.Certificate;
15import java.security.cert.CertificateFactory;
16import java.util.ArrayList;
17
18import javax.net.ssl.HttpsURLConnection;
19import javax.net.ssl.SSLContext;
20import javax.net.ssl.TrustManagerFactory;
21
22import javax.security.cert.X509Certificate;
23
24import android.os.AsyncTask;
25import android.os.Bundle;
26import android.os.Environment;
27import android.app.Activity;
28import android.app.AlertDialog;
29import android.app.Dialog;
30import android.app.ProgressDialog;
31import android.content.DialogInterface;
32import android.util.Log;
33import android.view.Menu;
34import android.view.View;
35import android.view.View.OnClickListener;
36import android.widget.Button;
37import android.widget.Toast;
38
39public class MainActivity extends Activity {
40
41       
42        public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
43        public static final int DIALOG_EXCEPTION = 1;
44    private Button startBtn;
45    private ProgressDialog mProgressDialog;
46   
47   
48    File rootDir = Environment.getExternalStorageDirectory();
49   
50    String urlhttps = "https://tibisay.cenditel.gob.ve/trac/raw-attachment/wiki/WikiStart/actados.2.bdoc";
51   
52        @Override
53        protected void onCreate(Bundle savedInstanceState) {
54                super.onCreate(savedInstanceState);
55                setContentView(R.layout.activity_main);
56               
57                startBtn = (Button)findViewById(R.id.startBtn);
58        startBtn.setOnClickListener(new OnClickListener(){
59            public void onClick(View v) {
60                startDownload();
61            }
62        });
63        }
64       
65        private void startDownload() {
66        //String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
67        String url = "https://tibisay.cenditel.gob.ve/trac/raw-attachment/wiki/WikiStart/actados.2.bdoc";
68        //String url = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG";
69       
70        checkAndCreateDirectory("/midescarga");
71       
72        new DownloadFileAsync().execute(url, "false");
73    }
74       
75        @Override
76    protected Dialog onCreateDialog(int id) {
77        switch (id) {
78            case DIALOG_DOWNLOAD_PROGRESS:
79                mProgressDialog = new ProgressDialog(this);
80                mProgressDialog.setMessage("Downloading file..");
81                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
82                mProgressDialog.setCancelable(false);
83                mProgressDialog.show();
84                return mProgressDialog;
85            default:
86                return null;
87        }
88    }
89       
90class DownloadFileAsync extends AsyncTask<String, String, ArrayList<String>> {
91       
92        @Override
93        protected void onPreExecute() {
94            super.onPreExecute();
95            showDialog(DIALOG_DOWNLOAD_PROGRESS);
96        }
97
98        @Override
99        protected ArrayList<String> doInBackground(String... params) {
100            int count;
101
102            Log.d("doInBackground", params[0]);
103           
104            // resultArray [0] -> 0 para ruta de archivo valida
105            // resultArray [0] -> 1 ocurrio un error
106            // resultArray [1] -> ruta del archivo descargado
107            // resultArray [1] -> mensaje de la excepcion
108            ArrayList<String> resultArray = new ArrayList<String>();
109           
110           
111            try {
112                URL url = new URL(params[0]);
113               
114                int lenghtOfFile = 0;
115                InputStream input = null;
116               
117                if (url.getProtocol().equals("http")){
118                        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
119                        input = new BufferedInputStream(httpConnection.getInputStream());
120                        lenghtOfFile = httpConnection.getContentLength();
121                   
122                }else{ // https
123                       
124                        // ejecutar la descarga despues de haber aceptado que el certificado
125                        // no es conocido
126                        if (params[1].equals("true")){
127                                Log.d("***", "params[1].equals(true)");
128                               
129                                // descarga del certificado del servidor
130                                CertificateFactory cf = CertificateFactory.getInstance("X.509");
131                                InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.cenditel.gob.ve.pem"));
132                                //InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.pem"));
133                                Certificate ca;
134                                try {
135                                    ca = cf.generateCertificate(caInput);
136                                   
137                                    Log.d("", ca.toString());
138                                } finally {
139                                    caInput.close();
140                                }
141                                Log.d("***", "despues de Certificate ca");
142                                // Create a KeyStore containing our trusted CAs
143                                String keyStoreType = KeyStore.getDefaultType();
144                                KeyStore keyStore = KeyStore.getInstance(keyStoreType);
145                                keyStore.load(null, null);
146                                keyStore.setCertificateEntry("ca", ca);
147                                Log.d("***", "despues de crear KeyStore");
148                               
149                                // Create a TrustManager that trusts the CAs in our KeyStore
150                                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
151                                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
152                                tmf.init(keyStore);
153                                Log.d("***", "despues de crear TrustManager");
154
155                                // Create an SSLContext that uses our TrustManager
156                                SSLContext context = SSLContext.getInstance("TLS");
157                                context.init(null, tmf.getTrustManagers(), null);
158                                Log.d("***", "despues de crear SSLContext");
159                               
160                                HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
161                                Log.d("***", "despues de crear httpsConnection");
162                               
163                                httpsConnection.setSSLSocketFactory(context.getSocketFactory());
164                                Log.d("***", "despues de crear setSSLSocketFactory");
165                               
166                                //input = new BufferedInputStream(httpsConnection.getInputStream());
167                                input = httpsConnection.getInputStream();
168                               
169                                Log.d("***", "despues de crear BufferedInputStream");
170                               
171                                lenghtOfFile = httpsConnection.getContentLength();
172                                Log.d("***", "se acepto la excepcion");
173                               
174                        }else{                 
175                                HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
176                                input = new BufferedInputStream(httpsConnection.getInputStream());
177                                lenghtOfFile = httpsConnection.getContentLength();
178                        }
179                }
180               
181               
182
183                //int lenghtOfFile = conexion.getContentLength();
184                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
185
186                //InputStream input = new BufferedInputStream(url.openStream());               
187                //InputStream input = new BufferedInputStream(conexion.getInputStream());
188               
189                //OutputStream output = new FileOutputStream("/mnt/sdcard/TibisayMovil/ExtractedFiles/photo.jpg");
190               
191                //OutputStream output = new FileOutputStream(new File(rootDir+"/midescarga/", "foto.jpg"));
192                OutputStream output = new FileOutputStream(new File(rootDir, "acta.2.bdoc"));
193               
194                byte data[] = new byte[1024];
195
196                long total = 0;
197
198                while ((count = input.read(data)) != -1) {
199                    total += count;
200                    publishProgress(""+(int)((total*100)/lenghtOfFile));
201                    output.write(data, 0, count);
202                }
203
204                output.flush();
205               
206                resultArray.add("0");
207                resultArray.add(output.toString());
208               
209                output.close();
210                input.close();
211               
212               
213               
214            } catch (Exception e) {
215               
216                Log.e("Error: ", e.getMessage());
217                resultArray.add("1");
218                resultArray.add(e.toString());
219               
220               
221            }
222            //return null;
223            return resultArray;
224
225        }
226        protected void onProgressUpdate(String... progress) {
227             Log.d("ANDRO_ASYNC",progress[0]);
228             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
229        }
230
231        @Override
232        protected void onPostExecute(ArrayList<String> result) {
233            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
234            Toast.makeText(getApplicationContext(), "onPostExecute: "+ result.get(0), Toast.LENGTH_LONG).show();
235           
236            // ocurrio una excepcion
237            if (result.get(0).equals("1")){
238               
239               
240                // ocurrio un problema
241                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
242                builder.setMessage(result.get(1)).setTitle("Error al descargar el archivo");
243               
244                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
245                    public void onClick(DialogInterface dialog, int id) {
246                        // User clicked OK button
247               
248                        Log.d("***", "DownloadFileAsync().execute(urlhttps, true)");
249                        Toast.makeText(getApplicationContext(), "DownloadFileAsync().execute(urlhttps, true)", Toast.LENGTH_LONG).show();
250                        // pasar como segundo argmento que se acepta que el sertivor es desconocido
251                        new DownloadFileAsync().execute(urlhttps, "true");
252                    }
253                });
254                builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
255                    public void onClick(DialogInterface dialog, int id) {
256                        // User cancelled the dialog
257                    }
258                });
259                AlertDialog dialog = builder.create();
260                dialog.show();
261               
262               
263               
264            }else{
265               
266               
267               
268               
269            }
270           
271                   
272        }
273       
274     
275       
276    }
277
278        //function to verify if directory exists
279        public void checkAndCreateDirectory(String dirName){
280               
281                File new_dir = new File( rootDir + dirName );
282                if( !new_dir.exists() ){
283                       
284                        Toast.makeText(getApplicationContext(), "checkAndCreateDirectory", Toast.LENGTH_SHORT).show();
285                        if(!new_dir.mkdirs()){
286                                Toast.makeText(getApplicationContext(), "FALLO checkAndCreateDirectory", Toast.LENGTH_SHORT).show();   
287                        }
288                }
289        }
290
291}
Note: See TracBrowser for help on using the repository browser.