Android DownloadManager SSL客户端证书认证

时间:2018-08-28 08:58:30

标签: android authentication ssl client

我想从我自己的托管服务器(使用自签名证书保护)下载文件。服务器本身需要根据请求验证客户端。现在,我想使用Android客户端中的下载管理器从服务器下载文件,但是似乎无法使用DownloadManager验证我的Android客户端。

如果我仅使用下载管理器坚持下载文件该怎么办,有什么方法可以自定义下载管理器类以进行身份​​验证以及信任服务器?

注意:使用自定义HttpClient调用,Api调用已经可以使用。

HttpCall代码:

public int HttpsCall()
{
    int version=0;
    if(Build.VERSION.SDK_INT>9)
    {
        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    DefaultHttpClient client = new MyHttpClient(getApplicationContext());

    HttpGet httpGet = new HttpGet("https://someurl/CheckVersionApi.php");
    try {
        HttpResponse response=null;
        response= client.execute(httpGet);

        if(response!=null)
        {
            Toast.makeText(this, "Null nahi h", Toast.LENGTH_SHORT).show();
        }


        HttpEntity httpEntity = response.getEntity();

        InputStream is = httpEntity.getContent();
        BufferedReader read = new BufferedReader(new InputStreamReader(is));
        String query = null;

        while ((query = read.readLine()) != null) {
            Log.d("Responce ", "" + query);
            Toast.makeText(this, ""+query, Toast.LENGTH_SHORT).show();
            version= Integer.valueOf(query);
        }
        Log.d("Responce", String.valueOf(response.getStatusLine().getStatusCode()));

    } catch (IOException e) {
        e.printStackTrace();
    }

    return version;
}

HTTP CLASS:

public class MyHttpClient extends DefaultHttpClient {

final Context context;

public MyHttpClient(Context context) {
    this.context = context;
}

@Override
protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    Toast.makeText(context, "CreateClient", Toast.LENGTH_SHORT).show();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // Register for port 443 our SSLSocketFactory with our keystore to the ConnectionManager
    registry.register(new Scheme("https", newSslSocketFactory(), 443));
    return new SingleClientConnManager(getParams(), registry);
}

private SSLSocketFactory newSslSocketFactory() {
    try {
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        Toast.makeText(context, "Keystore", Toast.LENGTH_SHORT).show();
        // Get the raw resource, which contains the keystore with your trusted certificates (root and any intermediate certs)

        File file=new File("storage/emulated/0","clienttruststore.bks/");
        FileInputStream in =new FileInputStream(file);
                //context.getResources().openRawResource(R.raw.clienttruststore);
        KeyStore keystore = KeyStore.getInstance("BKS");
        Toast.makeText(context, "Keystore", Toast.LENGTH_SHORT).show();
        File file1=new File("storage/emulated/0","client.bks/");
        FileInputStream in1 =new FileInputStream(file1);


        // / Get the raw resource, which contains the keystore with your trusted certificates (root and any intermediate certs)
       // InputStream in1 = context.getResources().openRawResource(R.raw.client);
        try {
            // Initialize the keystore with the provided trusted certificates.
            // Also provide the password of the keystore
            trusted.load(in, "qazwsx@123".toCharArray());
            keystore.load(in1, "qazwsx@123".toCharArray());
        } finally {
            in.close();
        }


        // Pass the keystore to the SSLSocketFactory. The factory is responsible for the verification of the server certificate.
       // SSLSocketFactory sf = new SSLSocketFactory(trusted);
        SSLSocketFactory sf = new SSLSocketFactory(SSLSocketFactory.TLS, keystore, "qazwsx@123",
                   trusted, null, null);

        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Toast.makeText(context, "KeystoreEnd", Toast.LENGTH_SHORT).show();
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

}

下载文件功能:

 private void downloadAndInstall() {

   notificationManager.cancel(100);
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse("https://someurl/apk/new.apk"));

    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "new.apk");

/////// HERE,我要使用具有客户端身份验证的下载管理器下载.APK +信任​​服务器

    enqueue = dm.enqueue(request);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Downloading..."); // Setting Message
    progressDialog.setTitle("Update"); // Setting Title
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
    progressDialog.show(); // Display Progress Dialog
    progressDialog.setCancelable(false);
    new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(2500);
            } catch (Exception e) {
                e.printStackTrace();
            }
          //  progressDialog.dismiss();
        }
    }).start();
    new android.os.Handler().postDelayed(
            new Runnable() {
                public void run() {

                    Toast.makeText(ShowNote.this, "Check your network", Toast.LENGTH_SHORT).show();

                    progressDialog.dismiss();
                    CancelDownloads();
                    finish();



                }
            }, 60000);


    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();


            if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {


                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                DownloadManager dm =(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
                dm.remove(downloadId);

            }
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "Download Completed", Toast.LENGTH_LONG).show();
                }
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(enqueue);

                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

//////////////////////////////

                        /////////////////////////////////////




                        Log.d("ainfo", uriString);

                        if(downloadId == c.getInt(0)) {
                            Log.d("DOWNLOAD PATH:", c.getString(c.getColumnIndex("local_uri")));


                            Log.d("isRooted:",String.valueOf(isRooted()));
                            if(isRooted()==false){
                                //if your device is not rooted
                                Uri uri= FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider",new File(Environment.getExternalStorageDirectory() + "/Download/"+"new.apk"));

                                Intent intent_install = new Intent(Intent.ACTION_VIEW);
                                intent_install.setDataAndType(uri, "application/vnd.android.package-archive");

                                intent_install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                intent_install.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);



                                Log.d("phone path",Environment.getExternalStorageDirectory() + "/Download/"+"new.apk");
                                startActivity(intent_install);

                                Toast.makeText(getApplicationContext(), "App Installing", Toast.LENGTH_LONG).show();
                                finish();
                            }else{
                                //if your device is rooted then you can install or update app in background directly
                                Toast.makeText(getApplicationContext(), "App Installing...Please Wait", Toast.LENGTH_LONG).show();
                                File file = new File("/mnt/sdcard/Download/new.apk");
                                Log.d("IN INSTALLER:", "/mnt/sdcard/Download/new.apk");
                                if(file.exists()){
                                    try {
                                        String command;
                                        Log.d("IN File exists:","/mnt/sdcard/Download/new.apk");

                                        command = "pm install -r " + "/mnt/sdcard/Download/new.apk";
                                        Log.d("COMMAND:",command);
                                        Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
                                        proc.waitFor();
                                        Toast.makeText(getApplicationContext(), "App Installed Successfully", Toast.LENGTH_LONG).show();

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
                c.close();
            }
        }
    };

    registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

0 个答案:

没有答案