在模块的 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"
}
}
}
}
最佳答案
好吧,您的代码中有几个问题:
一、withInputStream
和 withOutputStream
是对 Java 类的 Groovy JDK 增强 URL
和 File
.这与任何 Gradle 功能无关,仅适用,因为 Gradle 构建在 Groovy 之上。据我所知,无法将凭据传递给 withInputStream
,因此它仅适用于公开可用的资源。
关于代码 fragment 的第二部分,让我们先看看 buildscript
堵塞。它是一个特殊的 Gradle block ,总是首先被评估(并且必须在 build.gradle
文件的顶部)。这样做的原因是,这个 block 基本上是为您的构建脚本(又名 build.gradle
文件)提供设置。通常这个 block 定义 repositories
和 dependencies
需要解决构建脚本才能工作的问题(例如插件)。常规项目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/