如何在Groovy中获得REST响应?

Liv*_*osu 6 rest groovy

我必须在Web应用程序中编写一个小脚本。该Web应用程序有其局限性,但与以下在线控制台类似:https : //groovyconsole.appspot.com/,因此,如果在此处运行,它也应适用于我的问题。

我需要解析一个JSON响应。为简单起见,我使用自己的Web API用C#开发,当我在浏览器中输入链接(http:// localhost:3000 / Test)时,它给出了以下字符串:

{"Code":1,"Message":"This is just a test"}
Run Code Online (Sandbox Code Playgroud)

我想使用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()
Run Code Online (Sandbox Code Playgroud)

(摘自此处:http : //rest.elkstein.org/2008/02/using-rest-in-groovy.html

但是它不能识别import groovyx.net.http.RESTClient。您可以尝试在提供的groovy Web Sonsole中对其进行测试,然后会收到错误消息。

我尝试过,import groovyx.net.http.RESTClient.*但仍然没有成功。

Tom*_*rre 10

我试图找到一个现有的 REST 客户端来使用,但最终我总是创建自己的。我主要在 Jenkins 管道中使用它,如下所示:

new RestClient(this,"http://some-server.domain/gitlab")
 .get('/api/v4/projects/' + repo.id + '/hooks')
 .each { hook ->
  println "Hook: " + hook
 }
Run Code Online (Sandbox Code Playgroud)

这是实际的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)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ter 5

这是一个简单的Groovy脚本,该脚本将HTTP POST发送到在线服务器并使用解析响应JsonSlurper

该脚本可以在您的计算机上独立运行。它可能无法在在线Groovy REPL中使用。它使用Apache HTTPClient jar,它通过添加到类路径中@Grab

对于一个项目,不会使用这种方法,而是将jar添加到Gradle中的类路径中。