use*_*381 26 rest groovy gradle
嗨,我需要调用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 ->
}
}
Run Code Online (Sandbox Code Playgroud)
tim*_*tes 19
你不能这样做吗?
new URL( 'http://username:password@myserver.com:8983/solr/select?q=*&wt=json' ).text
Run Code Online (Sandbox Code Playgroud)
JBa*_*uch 14
在没有外部库的情况下从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)
}
Run Code Online (Sandbox Code Playgroud)
use*_*381 12
这是工作的人
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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
Yan*_* Vo 12
这个问题在搜索引擎上的排名非常好,我一直在绊倒它。
但是,正如其他人评论的那样,我真的不喜欢接受的答案,因为它依赖于 curl。
所以这是一个完整的例子,没有任何先决条件(没有插件,没有 curl,...):
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 on first read
def resp = new JsonSlurper().parseText(req.getInputStream().getText())
logger.quiet "Response: ${resp}"
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在您的机器上运行它,因为它们使用公共开发 API。
我正在使用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']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27203 次 |
| 最近记录: |