android - Gradle 构建 : Server returned HTTP response code: 401 for URL https using artifactory

标签 android gradle android-gradle-plugin artifactory

在模块的 build.gradle 中,我正在尝试执行以下行

if (!jsonFile.exists()) {
    new URL(mapUrl).withInputStream{ i -> jsonFile.withOutputStream{ it << i }}
}
构建失败并出现以下错误:
Server returned HTTP response code: 401 for URL: https://artifactory.myurl.com/artifactory/myfile.json
我将凭据传递给我的 gradle 脚本,如下所示:
buildscript {
    repositories {
        google()
        jcenter()

        maven {
            url 'https://artifactory.myurl.com/artifactory/'
            credentials {
                username = "myuser"
                password = "mypwd"
            }
        }
    }
}

最佳答案

好吧,您的代码中有几个问题:
一、withInputStreamwithOutputStream是对 Java 类的 Groovy JDK 增强 URLFile .这与任何 Gradle 功能无关,仅适用,因为 Gradle 构建在 Groovy 之上。据我所知,无法将凭据传递给 withInputStream ,因此它仅适用于公开可用的资源。
关于代码 fragment 的第二部分,让我们先看看 buildscript堵塞。它是一个特殊的 Gradle block ,总是首先被评估(并且必须在 build.gradle 文件的顶部)。这样做的原因是,这个 block 基本上是为您的构建脚本(又名 build.gradle 文件)提供设置。通常这个 block 定义 repositoriesdependencies需要解决构建脚本才能工作的问题(例如插件)。常规项目dependencies和他们的repositories可以在 buildscript 之外定义堵塞。当其他任务(例如编译任务)需要它们时,它们会被解决。

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'example-plugins:my-fancy-plugin:0.0.1'
    }
}
// the build script stops here to resolve my-fancy-plugin from jcenter

repositories {
    jcenter()
}

dependencies {
    implementation 'example-libraries:my-cool-library:0.0.1'
}
// this won't be resolved directly, only if a task that needs *implementation* dependencies is run
repositories/dependencies机制主要用于解决*.jar用作基于 JVM 项目的依赖项的文件。存储库通常是 Maven 存储库。 Maven 存储库遵循特定的布局,因此依赖描述符(例如 example-libraries:my-cool-library:0.0.1 )将映射到 URL(例如 example/libraries/my-cool-library/0.0.1/my-cool-library-0.0.1.jar )。 Gradle 然后尝试从此 URL 下载依赖项。由于您的路径不遵循 Maven 存储库布局,因此您无法从 Maven 存储库下载文件。
对于您的用例,您可能根本不应该使用 Gradle 依赖项解析。有一个plugin允许使用 Gradle 任务下载文件(支持身份验证):
task downloadFile(type: Download) {
    src 'https://artifactory.myurl.com/artifactory/myfile.json'
    username = "myuser"
    password = "mypwd"
    dest buildDir
}
或者,您可以使用 custom repository layout 定义一个 Ivy 存储库。 .

关于android - Gradle 构建 : Server returned HTTP response code: 401 for URL https using artifactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63574872/

相关文章:

android - 如何查看 Android Studio 运行构建配置时执行的 gradle 命令?

android - 如何在Interactor/UseCase中获取CoroutineScope

java - 互联网连接异常失败

gradle - 为什么Gradle在我的插件中找错了位置?

Android Gradle 插件 1.1.0 - getNdkFolder() 不再找到,是否有替代品?

android - 更新到 AndroidX Libraries 和 Gradle 3.4.2 后出现的问题

android - Paypal 整合 - 如何?

Android Studio 错误 : 'command ' C:\Program Files\Java\jdk1. 7.0_75\bin\java.exe'' 已完成,退出值非零 2

java - gradle 包含传递运行时依赖作为编译依赖

java - Idea 不断将 Kotlin 的编译目标从 1.8 切换到 1.6