Gradle 构建:服务器返回 HTTP 响应代码:401 URL https 使用人工制品

Gradle build: Server returned HTTP response code: 401 for URL https using 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 是 Groovy JDK 在 Java 类 URLFile。这与任何 Gradle 功能无关,仅有效,因为 Gradle 构建在 Groovy 之上。据我所知,无法将凭据传递给 withInputStream,因此它仅适用于公开可用的资源。

关于代码片段的第二部分,让我们首先看一下 buildscript 块。它是一个特殊的 Gradle 块,总是首先被评估(并且必须在 build.gradle 文件的顶部)。这样做的原因是这个块基本上为您的构建脚本(又名 build.gradle 文件)提供了一个设置。通常这个块定义了构建脚本需要解析的 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机制主要用于解析作为JVM-based项目依赖的*.jar文件。存储库通常是 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 存储库