我必须在网络应用中编写一个小脚本。这个网络应用程序有其局限性但与此在线控制台类似:https://groovyconsole.appspot.com/所以如果它在这里工作,它也适用于我的问题。
我需要解析JSON响应。为简单起见,我使用C#开发了自己的Web API,当我在浏览器中输入链接(http://localhost:3000/Test)时,它会给出这个字符串:
{"Code":1,"Message":"This is just a test"}
我想得到这个字符串,然后解析它,我猜JsonSplunker。经过数小时的研究,最引人注目的样本将是:
import groovyx.net.http.RESTClient
def client = new RESTClient( 'http://www.acme.com/' )
def resp = client.get( path : 'products/3322' ) // ACME boomerang
assert resp.status == 200 // HTTP response code; 404 means not found, etc.
println resp.getData()
(取自此处:http://rest.elkstein.org/2008/02/using-rest-in-groovy.html)
然而,它无法识别import groovyx.net.http.RESTClient
。您可以尝试在提供的groovy web sonsole中测试它,您将收到错误。
我尝试import groovyx.net.http.RESTClient.*
但仍然没有成功。
答案 0 :(得分:3)
Here is a simple Groovy script将HTTP POST发送到在线服务器并使用JsonSlurper
解析响应。
此脚本可以在您的计算机上独立运行;它可能不适用于在线Groovy REPL。它使用Apache HTTPClient jar,它通过@Grab
添加到类路径中。
对于项目,不会使用此方法,而是将jar添加到Gradle中的类路径中。
答案 1 :(得分:3)
如果问题在于导入swal({
type: 'question',
title: 'Confirm recipient details',
html: '<p style="color:#C00; padding-bottom:0px; margin-bottom:0px">
Cloud only terms and conditions</p>
<div class="swal_input_wrapper">
<div class="label_wrapper">Email: </div>
<input id="swal-input1" style="width:75%" class="swal2-input" autofocus><br/>
<div class="label_wrapper">Recipient: </div>
<input id="swal-input2" style="width:75%" class="swal2-input"></div><br/>
<div class="label_wrapper">Message: </div>
<textarea id="swal-input3" style="width:75%" class="swal2-textarea"></textarea>
</div>',
preConfirm: function() {
return new Promise(function(resolve) {
resolve([
$('#swal-input1').val(),
$('#swal-input2').val(),
$('#swal-input3').text()
]);
});
}
}).then(function(result) {
//values from inputs (results is an array)
email = result[0];
email_name = result[1];
email_message = result[2];
alert(email_name);
}).done();
,那么您就错过了依赖关系$('#swal-input3').text()
$('#swal-input3').val()
$('#swal-input3').html()
。
如果您只处理一个独立的Groovy脚本,您可以使用Groovy的Grape来获取依赖项。以下是groovyx.net.http.RESTClient
home page {<3}}中的一个示例:
org.codehaus.groovy.modules.http-builder:http-builder
如果您的网络应用使用依赖关系系统(例如Gradle),那么您可以使用它而不是RESTClient
。
答案 2 :(得分:0)
我试图找到一个现有的REST客户端来使用,但是我总是最终创建自己的REST客户端。我主要在Jenkins管道中使用它,如下所示:
new RestClient(this,"http://some-server.domain/gitlab")
.get('/api/v4/projects/' + repo.id + '/hooks')
.each { hook ->
println "Hook: " + hook
}
这是实际的RestClient
:
package se.bjurr.jenkinssandbox
public class RestClient {
private def baseUrl
private def steps
public RestClient(def steps, def baseUrl='http://localhost') {
this.steps = steps
this.baseUrl = baseUrl
}
def get(def path) {
def responseText = ""
steps.withCredentials([steps.string(credentialsId: 'gitlab-token', variable: 'gitlabToken')]) {
steps.println "Using token: "+steps.env.gitlabToken +" to get \"" + baseUrl + path + "\""
def conn = null
try {
conn = new URL(baseUrl+path).openConnection();
conn.setRequestMethod("GET")
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestProperty("Private-Token", steps.env.gitlabToken)
conn.setDoOutput(false)
def postRC = conn.getResponseCode();
responseText = conn.getInputStream().getText()
steps.println "Got: " + postRC + "\n"+responseText
} finally {
conn.disconnect()
}
//Because classic is serilizable
return new groovy.json.JsonSlurperClassic().parseText(responseText)
}
}
def delete(def path) {
def responseText = ""
steps.withCredentials([steps.string(credentialsId: 'gitlab-token', variable: 'gitlabToken')]) {
steps.println "Using token: "+steps.env.gitlabToken +" to delete \"" + baseUrl + path + "\""
def conn = null
try {
conn = new URL(baseUrl+path).openConnection();
conn.setRequestMethod("DELETE")
conn.setRequestProperty("Private-Token", steps.env.gitlabToken)
conn.setDoOutput(false)
def postRC = conn.getResponseCode();
responseText = conn.getInputStream().getText()
steps.println "Got: " + postRC + "\n"+responseText
} finally {
conn.disconnect()
}
}
}
def post(def path) {
def responseText = ""
steps.withCredentials([steps.string(credentialsId: 'gitlab-token', variable: 'gitlabToken')]) {
steps.println "Using token: "+steps.env.gitlabToken +" to post \"" + baseUrl + path + "\""
def conn = null
try {
conn = new URL(baseUrl+path).openConnection();
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestProperty("Private-Token", steps.env.gitlabToken)
conn.setDoOutput(false)
def postRC = conn.getResponseCode();
responseText = conn.getInputStream().getText()
steps.println "Got: " + postRC + "\n"+responseText
} finally {
conn.disconnect()
}
//Because classic is serilizable
return new groovy.json.JsonSlurperClassic().parseText(responseText)
}
}
def post(def path, def payload) {
def responseText = ""
steps.withCredentials([steps.string(credentialsId: 'gitlab-token', variable: 'gitlabToken')]) {
String jsonString = new groovy.json.JsonBuilder(payload).toPrettyString()
steps.println "Using token: "+steps.env.gitlabToken +" to post \"" + baseUrl + path + "\" with:\n"+jsonString
def conn = null
try {
conn = new URL(baseUrl+path).openConnection();
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestProperty("Private-Token", steps.env.gitlabToken)
conn.setDoOutput(true)
conn.getOutputStream().write(jsonString.getBytes("UTF-8"));
def postRC = conn.getResponseCode();
responseText = conn.getInputStream().getText()
steps.println "Got: " + postRC + "\n"+responseText
} finally {
conn.disconnect()
}
//Because classic is serilizable
return new groovy.json.JsonSlurperClassic().parseText(responseText)
}
}
}