Skip to content

Gradle 7+ 中允许使用不安全的 HTTP 协议

问题描述

当升级到 Android Studio Arctic Fox 和 Gradle 7+ 版本后,可能会遇到以下错误:

A problem occurred configuring root project 'so10'.
> Could not resolve all dependencies for configuration ':classpath'.
   > Using insecure protocols with repositories, without explicit opt-in, is unsupported.

这个错误特别指出使用了不安全的协议(如 HTTP)而没有显式允许,导致构建失败。

解决方案

方案一:显式允许不安全协议(推荐)

对于 Gradle 7+ 版本,需要在 maven 闭包中明确设置 allowInsecureProtocol 属性:

groovy
repositories {
    maven {
        url "http://oss.sonatype.org/content/repositories/snapshots"
        allowInsecureProtocol = true
    }
    // 其他仓库配置...
}
kotlin
repositories {
    maven {
        url = uri("http://oss.sonatype.org/content/repositories/snapshots")
        isAllowInsecureProtocol = true
    }
    // 其他仓库配置...
}

注意事项

  • Kotlin DSL 中使用的是 isAllowInsecureProtocol 属性
  • Groovy DSL 中使用的是 allowInsecureProtocol 属性
  • 必须为每个使用 HTTP 协议的仓库单独设置此属性

方案二:升级到 HTTPS 协议(最佳实践)

如果仓库支持 HTTPS,强烈建议将 URL 从 HTTP 升级到 HTTPS:

groovy
// 将
maven { url 'http://oss.sonatype.org/content/repositories/snapshots' }
// 改为
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }

方案三:处理应用脚本的情况

如果错误是因为应用远程脚本导致的:

groovy
// 之前的写法(会报错)
apply from: "http://mycompany.com/buildscript.gradle"

// 修正后的写法
apply from: resources.text.fromInsecureUri("http://mycompany.com/buildscript.gradle")

备用方法:使用方法调用

在某些情况下,直接赋值可能不生效,可以尝试使用方法调用:

groovy
maven {
    url "http://myinsecure/repository..."
    setAllowInsecureProtocol(true)
}

完整配置示例

groovy
repositories {
    maven {
        url "http://oss.sonatype.org/content/repositories/snapshots"
        allowInsecureProtocol = true
    }
    maven {
        url "http://storage.googleapis.com/r8-releases/raw"
        allowInsecureProtocol = true
    }
    maven { url "https://jitpack.io" }
    maven { url 'https://raw.github.com/Raizlabs/maven-releases/master/releases' }
    maven { url "https://plugins.gradle.org/m2/" }
    maven { url 'https://maven.google.com' }
    google()
    mavenCentral()
}

安全建议

虽然可以临时允许不安全协议,但从安全角度考虑,建议:

  1. 优先使用 HTTPS 协议
  2. 如果必须使用 HTTP,确保来源可靠
  3. 定期检查并更新到支持 HTTPS 的仓库

通过上述方法,可以解决 Gradle 7+ 版本中因使用不安全 HTTP 协议而导致的构建错误。