美文网首页
(快速)AndroidStudio报错ERROR: Cause:

(快速)AndroidStudio报错ERROR: Cause:

作者: Analyas | 来源:发表于2020-03-19 20:29 被阅读0次

    转载请注明出处

    接上篇,如果你需要知道原理,请查看我的这篇文章https://www.jianshu.com/p/89ca5b635d3f,如果你不需要了解那么多,并且只想快速的装好你的AndroidStudio,那就请按着教程愉快的开始吧!

    目录

    • 1.安装证书
    • 2.使用阿里仓库
    • 3.刷新缓存使配置生效

    1.安装证书

    (1)准备安装证书的java代码

    注意,该文件与上篇文章的文件内容不一样,所以不要使用上一篇文章InstallCert.java文件来进行下面的操作!!该文件集成了新建项目要用到的域名"dl.google.com", "maven.aliyun.com", "jcenter.bintray.com", "d29vzk4ow07wi7.cloudfront.net",后续操作会一次性添加这些证书,如果你还有其它的域名,在代码中的hosts加上即可

    • 点击下载:InstallCert.java(推荐,如果打开是源码而不是文件,右键浏览器另存为,保存名为InstallCert.java即可)
    • 也可以新建一个InstallCert.java文件,然后复制以下代码。
    /*
     * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     *   - Redistributions of source code must retain the above copyright
     *     notice, this list of conditions and the following disclaimer.
     *
     *   - Redistributions in binary form must reproduce the above copyright
     *     notice, this list of conditions and the following disclaimer in the
     *     documentation and/or other materials provided with the distribution.
     *
     *   - Neither the name of Sun Microsystems nor the names of its
     *     contributors may be used to endorse or promote products derived
     *     from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
     * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
    
    import java.io.*;
    import java.security.*;
    import java.security.cert.*;
    import java.util.Scanner;
    import javax.net.ssl.*;
    
    public class InstallCert {
        public static int certCount = 0;
        public static StringBuilder stringBuilder = new StringBuilder();
        public static void main(String[] args) {
            //if you hava other host, you can add host to it
            String[] hosts = new String[]{"dl.google.com", "maven.aliyun.com", "jcenter.bintray.com", "d29vzk4ow07wi7.cloudfront.net"};
            for (String host : hosts) {
                addCert(host);
            }
    
            System.out.println("Success Add Cert Count:"+certCount);
            System.out.println("Add Error:"+stringBuilder.toString());
        }
    
        public static void addCert(String host) {
            try {
                int port = 443; //Server Port
                String p = "changeit"; //default is changeit
                char[] passphrase = p.toCharArray();
                String tfilePath = new File(new File("").getAbsolutePath()).getParentFile().getAbsolutePath();
                System.out.println(new File("").getAbsolutePath());
                File file = new File(tfilePath + "/jre/lib/security/cacerts");
                System.out.println("Loading KeyStore " + file.getAbsolutePath() + "...");
                InputStream in = new FileInputStream(file);
                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(in, passphrase);
                in.close();
    
                SSLContext context = SSLContext.getInstance("TLS");
                TrustManagerFactory tmf =
                        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(ks);
                X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
                SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
                context.init(null, new TrustManager[]{tm}, null);
                SSLSocketFactory factory = context.getSocketFactory();
    
                System.out.println("Opening connection to " + host + ":" + port + "...");
                SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
                socket.setSoTimeout(10000);
                try {
                    System.out.println("Starting SSL handshake...");
                    socket.startHandshake();
                    socket.close();
                    System.out.println();
                    System.out.println("No errors, certificate is already trusted");
                } catch (SSLException e) {
                    System.out.println();
                    e.printStackTrace(System.out);
                }
    
                X509Certificate[] chain = tm.chain;
                if (chain == null) {
                    System.out.println("Could not obtain server certificate chain");
                    return;
                }
    
                BufferedReader reader =
                        new BufferedReader(new InputStreamReader(System.in));
    
                System.out.println();
                System.out.println("Server sent " + chain.length + " certificate(s):");
                System.out.println();
                MessageDigest sha1 = MessageDigest.getInstance("SHA1");
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                for (int i = 0; i < chain.length; i++) {
                    X509Certificate cert = chain[i];
                    System.out.println
                            (" " + (i + 1) + " Subject " + cert.getSubjectDN());
                    System.out.println("   Issuer  " + cert.getIssuerDN());
                    sha1.update(cert.getEncoded());
                    System.out.println("   sha1    " + toHexString(sha1.digest()));
                    md5.update(cert.getEncoded());
                    System.out.println("   md5     " + toHexString(md5.digest()));
                    System.out.println();
                }
    
                //jump user input
                System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
                int k = 0;
                X509Certificate cert = chain[k];
                String alias = host + "-" + (k + 1);
                ks.setCertificateEntry(alias, cert);
                OutputStream out = new FileOutputStream(file);
                ks.store(out, passphrase);
                out.close();
    
                System.out.println();
                System.out.println(cert);
                System.out.println();
                System.out.println
                        ("Added certificate to keystore 'jssecacerts' using alias '"
                                + alias + "'");
                certCount++;
            } catch (Exception e) {
                e.printStackTrace();
                stringBuilder.append(host+"=======");
            }
        }
    
        private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
    
        private static String toHexString(byte[] bytes) {
            StringBuilder sb = new StringBuilder(bytes.length * 3);
            for (int b : bytes) {
                b &= 0xff;
                sb.append(HEXDIGITS[b >> 4]);
                sb.append(HEXDIGITS[b & 15]);
                sb.append(' ');
            }
            return sb.toString();
        }
    
        private static class SavingTrustManager implements X509TrustManager {
    
            private final X509TrustManager tm;
            private X509Certificate[] chain;
    
            SavingTrustManager(X509TrustManager tm) {
                this.tm = tm;
            }
    
            public X509Certificate[] getAcceptedIssuers() {
                throw new UnsupportedOperationException();
            }
    
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                throw new UnsupportedOperationException();
            }
    
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                this.chain = chain;
                tm.checkServerTrusted(chain, authType);
            }
        }
    }
    

    (2)将证书文件放到AndroidStudio的java目录里
    把InstallCert.java移动到 “AndroidStudio安装目录/jre/bin”目录下,注意!不是jre/jre/bin目录下,不要弄错了,如下图所示

    1.jpg

    (3)导入证书

    • 以管理员身份打开cmd进入到该目录,您也可以在地址栏直接输入cmd可快速进入该目录,如图所示


      3.png
      4.png
    • 在cmd输入javac InstallCert.java然后回车编译代码, 随后输入java InstallCert运行程序,等待程序结束运行即可!
    C:\FastSoftwore\AndroidStudio\jre\bin>javac InstallCert.java
    
    C:\FastSoftwore\AndroidStudio\jre\bin>java InstallCert
    
    • 当cmd窗口最后出现Add Error为空表示所有证书导入完成


      5.png

    2.使用阿里仓库

    (1)加入阿里仓库地址

    这个步骤可以加快你项目构建的速度,为了节省您的时间,推荐你将阿里仓库加入到你的项目中

    • 打开Project级别的build.gradle文件,google()之上加入以下代码,建议加在最上面,以便优先使用该地址(如图所示,有两处地方需要加上)
            //阿里仓库服务,加快依赖下载速度
            maven{ url 'https://maven.aliyun.com/repository/google/'}
            maven{ url 'https://maven.aliyun.com/repository/jcenter/'}
    
    6.png

    3.刷新缓存使配置生效

    • ** 点击File->Invalidate Caches / Restart ** 刷新缓存并重启


      7.png
    • ** 在弹出的窗口中选择Invalidate and Restart 确认刷新缓存并重启 **


      8.png

      -- ** 当AndroidStudio自动重启后,发现运行按钮是灰色的,并且右下角也没有Gradle进程在运行,可以尝试点击File->Sync Project with Gradle Files来同步项目


      9.png

    到这一步,问题基本已经解决,如果问题没解决,你应该检查你是否改过AndroidStudio使用的java环境,基本上AndroidStudio默认使用自带的java环境,除非你手动设置过,如果确实没动过,可尝试多同步一下项目看看(File->Sync Project with Gradle Files),因为有时候网络不好,导致下载失败,也会引起这个问题】(完)

    【如果该文章解决了您的问题,可以给我点个赞哦,欢迎加入我的Q群一起学习!(Q群:202253703)】

    相关文章

      网友评论

          本文标题:(快速)AndroidStudio报错ERROR: Cause:

          本文链接:https://www.haomeiwen.com/subject/jgmcyhtx.html