1. 程式人生 > >JCenter下載太慢?教你修改Maven倉庫地址為國內映象

JCenter下載太慢?教你修改Maven倉庫地址為國內映象

近來遷移了一些專案到Android Studio,採用Gradle構建確實比原來的Ant方便許多。但是編譯時下載依賴的網速又著實令人蛋疼不已。

如果能切換到國內的Maven映象倉庫,如開源中國的Maven庫,又或者是換成自建的Maven私服,那想必是極好的。

一個簡單的辦法,修改專案根目錄下的build.gradle,將jcenter()或者mavenCentral()替換掉即可:

allprojects {
    repositories {
        maven{ url 'http://maven.oschina.net/content/groups/public/'}
    }
}

但是架不住專案多,難不成每個都改一遍麼?
自然是有省事的辦法,將下面這段Copy到名為init.gradle檔案中,並儲存到USER_HOME/.gradle/資料夾下即可。

allprojects{
    repositories {
        def REPOSITORY_URL = 'http://maven.oschina.net/content/groups/public'
        all { ArtifactRepository repo ->
            if(repo instanceof MavenArtifactRepository){
                def url = repo.url.toString()
                if (url.startsWith('https://repo1.maven.org/maven2') || url.startsWith('https://jcenter.bintray.com/')) {
                    project.logger.lifecycle "Repository ${repo.url} replaced by $REPOSITORY_URL."
                    remove repo
                }
            }
        }
        maven {
            url REPOSITORY_URL
        }
    }
}

init.gradle檔案其實是Gradle的初始化指令碼(Initialization Scripts),也是執行時的全域性配置。

如果碰到如下錯誤,多嘗試幾次就好了:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'fresco'.
> Could not resolve all dependencies for configuration ':classpath'.
   > Could not download httpcore.jar (org.apache.httpcomponents:httpcore:4.1
) > Could not get resource 'https://jcenter.bintray.com/org/apache/httpcomponents/httpcore/4.1/httpcore-4.1.jar'. > SSL peer shut down incorrectly * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED