问题描述
在模块的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类URL
和File
上的Groovy JDK增强。这与Gradle的任何功能都没有关系,只能使用,因为Gradle构建在Groovy之上。据我所知,无法将凭据传递给withInputStream
,因此它仅适用于公开可用的资源。
关于代码段的第二部分,让我们首先看一下buildscript
块。这是一个特殊的Gradle块,始终会首先对其进行评估(并且必须位于build.gradle
文件的顶部)。这样做的原因是,该块基本上是为您的构建脚本(也称为build.gradle
文件)提供的设置。通常,此块定义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定义常春藤存储库。