您好我需要在没有任何第三方插件的情况下将REST服务作为buildscript(Gradle)的一部分来调用,我怎么能使用Groovy来做到这一点?
(我的第一次尝试)
repositories {
mavenCentral()
}
dependencies {
complie "org.codehaus.groovy.modules.http-builder:http-builder:0.5.2"
}
task hello {
def http = new HTTPBuilder("http://myserver.com:8983/solr/select?q=*&wt=json")
http.auth.basic 'username', 'password'
http.request(GET, JSON ) { req ->
}
}
答案 0 :(得分:18)
你不能这样做吗
new URL( 'http://username:password@myserver.com:8983/solr/select?q=*&wt=json' ).text
答案 1 :(得分:12)
在没有外部库的情况下从groovy调用REST的最简单方法是执行CURL。这是调用Artifactory,获取JSON并解析它的一个例子:
import groovy.json.JsonSlurper
task hello {
def p = ['curl', '-u', '"admin:password"', "\"http://localhost:8081/api/storage/libs-release-local?list&deep=1\""].execute()
def json = new JsonSlurper().parseText(p.text)
}
答案 2 :(得分:11)
这是工作人员
import java.io.*
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.EncoderRegistry
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2'
}
}
task hello {
def http = new groovyx.net.http.HTTPBuilder("http://local.com:8983/solr/update/json")
http.request(POST, JSON ) { req ->
req.body{
}
response.success = { resp, reader ->
println "$resp.statusLine Respond rec"
}
}
}
答案 3 :(得分:7)
我正在使用JsonSlurper它看起来非常简单并且与操作系统无关:
import groovy.json.JsonSlurper
String url = "http://<SONAR_URL>/api/qualitygates/project_status?projectKey=first"
def json = new JsonSlurper().parseText(url.toURL().text)
print json['projectStatus']['status']
答案 4 :(得分:0)
这个问题在搜索引擎上的排名是如此之好,以至于我一直之以鼻。
但是,正如其他人所评论的那样,我不太喜欢被接受的答案,因为它依赖于卷曲。
因此,这是一个完整的示例,没有任何先决条件(无插件,无卷曲,...):
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
task getExample {
doLast {
def req = new URL('https://jsonplaceholder.typicode.com/posts/1').openConnection()
logger.quiet "Status code: ${req.getResponseCode()}"
def resp = new JsonSlurper().parseText(req.getInputStream().getText())
logger.quiet "Response: ${resp}"
}
}
task postExample {
doLast {
def body = [title: "foo", body: "bar", userId: 1]
def req = new URL('https://jsonplaceholder.typicode.com/posts').openConnection()
req.setRequestMethod("POST")
req.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
req.setDoOutput(true)
req.getOutputStream().write(JsonOutput.toJson(body).getBytes("UTF-8"))
logger.quiet "Status code: ${req.getResponseCode()}" // HTTP request done one first read
def resp = new JsonSlurper().parseText(req.getInputStream().getText())
logger.quiet "Response: ${resp}"
}
}
当他们使用公共开发API时,您可以在其上运行它。