天天看点

android手机访问https网站证书信任问题Trust anchor for certification path not found

解决此问题

public class MethodForJS {


    private Context mContext;

    private String filePath = Environment.getExternalStorageDirectory().getPath() + "/download/";


    public MethodForJS(Context mContext) {
        this.mContext = mContext;
    }

    @JavascriptInterface
    public void Downloadfile(final String path) {
        Log.e("path", path);
        final String downloadUrl = Constants.FILE_HEAD + path;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    String fileName = FileUtil.getFileName(downloadUrl);
                    Log.e("fileName", fileName);

                    URL url = new URL(downloadUrl);
                    HttpURLConnection con;

                    trustAllHosts();//依赖此方法解决
                    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                    https.setHostnameVerifier(DO_NOT_VERIFY);//依赖此方法解决

                    con = https;

                    con.setReadTimeout(5000);
                    con.setConnectTimeout(5000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
                    if (con.getResponseCode() == 200) {
                        InputStream is = con.getInputStream();//获取输入流
                        FileOutputStream fileOutputStream = null;//文件输出流
                        if (is != null) {

                            File file = new File(filePath);
                            if (!file.exists()) {
                                file.mkdirs();
                            }

                            fileOutputStream = new FileOutputStream(new File(filePath, fileName));//指定文件保存路径,代码看下一步

                            byte[] buf = new byte[1024];
                            int ch;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
                            }
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }

                        //下载完成

                        File file0 = new File(filePath + fileName);

  
                        if (isAvilible(mContext, "cn.wps.moffice_eng")) {
                            if (file0.exists()) {
                                try {
                                    mContext.startActivity(OpenFiles.getWordFileIntent(mContext, file0));
                                }catch (Exception e){
                                    e.printStackTrace();
                                }

                            }
                        } else {
                            Uri uri = Uri.parse("market://details?id=cn.wps.moffice_eng");            // 从市场上下载
                            Intent it = new Intent(Intent.ACTION_VIEW, uri);            // 直接从指定网址下载
                            mContext.startActivity(it);
                        }


                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }


    public static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        // Android use X509 cert
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };


    private boolean isAvilible(Context context, String packageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo("cn.wps.moffice_eng", 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            System.out.println("not installed");
        } else {
            System.out.println("is installed");
        }
        final PackageManager packageManager = context.getPackageManager();//获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);//判断pName中是否有目标程序的包名,有TRUE,没有FALSE
    }
}           

插个眼 retrofit2中ssl的Trust anchor for certification path not found问题:

https://www.cnblogs.com/maomishen/p/5403301.html