轉(zhuǎn)載請注明出處。
接上篇昭殉,如果你需要知道原理撤防,請查看我的這篇文章http://www.reibang.com/p/89ca5b635d3f,如果你不需要了解那么多法严,并且只想快速的裝好你的AndroidStudio村砂,那就請按著教程愉快的開始吧栈暇!
目錄
- 1.安裝證書
- 2.使用阿里倉庫
- 3.刷新緩存使配置生效
1.安裝證書
(1)準備安裝證書的java代碼
注意,該文件與上篇文章的文件內(nèi)容不一樣箍镜,所以不要使用上一篇文章InstallCert.java文件來進行下面的操作T雌怼!該文件集成了新建項目要用到的域名"dl.google.com", "maven.aliyun.com", "jcenter.bintray.com", "d29vzk4ow07wi7.cloudfront.net"色迂,后續(xù)操作會一次性添加這些證書香缺,如果你還有其它的域名,在代碼中的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目錄下适袜,不要弄錯了柄错,如下圖所示
(3)導入證書
-
以管理員身份打開cmd進入到該目錄,您也可以在地址欄直接輸入cmd可快速進入該目錄苦酱,如圖所示
- 在cmd輸入javac InstallCert.java然后回車編譯代碼售貌, 隨后輸入java InstallCert運行程序,等待程序結(jié)束運行即可疫萤!
C:\FastSoftwore\AndroidStudio\jre\bin>javac InstallCert.java
C:\FastSoftwore\AndroidStudio\jre\bin>java InstallCert
-
當cmd窗口最后出現(xiàn)Add Error為空表示所有證書導入完成
2.使用阿里倉庫
(1)加入阿里倉庫地址
這個步驟可以加快你項目構(gòu)建的速度颂跨,為了節(jié)省您的時間,推薦你將阿里倉庫加入到你的項目中
- 打開Project級別的build.gradle文件扯饶,google()之上加入以下代碼恒削,建議加在最上面,以便優(yōu)先使用該地址(如圖所示尾序,有兩處地方需要加上)
//阿里倉庫服務蔓同,加快依賴下載速度
maven{ url 'https://maven.aliyun.com/repository/google/'}
maven{ url 'https://maven.aliyun.com/repository/jcenter/'}
3.刷新緩存使配置生效
-
** 點擊File->Invalidate Caches / Restart ** 刷新緩存并重啟
-
** 在彈出的窗口中選擇Invalidate and Restart 確認刷新緩存并重啟 **
-- ** 當AndroidStudio自動重啟后,發(fā)現(xiàn)運行按鈕是灰色的蹲诀,并且右下角也沒有Gradle進程在運行,可以嘗試點擊File->Sync Project with Gradle Files來同步項目
到這一步弃揽,問題基本已經(jīng)解決脯爪,如果問題沒解決,你應該檢查你是否改過AndroidStudio使用的java環(huán)境矿微,基本上AndroidStudio默認使用自帶的java環(huán)境痕慢,除非你手動設置過,如果確實沒動過涌矢,可嘗試多同步一下項目看看(File->Sync Project with Gradle Files)掖举,因為有時候網(wǎng)絡不好,導致下載失敗娜庇,也會引起這個問題】(完)
【如果該文章解決了您的問題塔次,可以給我點個贊哦,歡迎加入我的Q群一起學習C恪(Q群:202253703)】