Liviu Sosu Liviu Sosu - 3 months ago 37
Groovy Question

How to get the REST response in Groovy?

I am familiar with Stackoverflow, I know I should not ask duplicate questions. but I really do not find the answer. I am new to Groovy, and I have to write a small script within a web app. This web app has it's limitations but is simillar to this online console https://groovyconsole.appspot.com/ so if it works here, should work for my problem as well.

I need to parse a json response. For simplicity I developed in C# my own web API and when I enter on the browser the link (http://localhost:3000/Test) it gives this string :

{"Code":1,"Message":"This is just a test"}


I want to get this string, and parse it afterwards, I guess with JsonSplunker. After hours of research, the most compelling sample would be this:

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()


(taken from here: http://rest.elkstein.org/2008/02/using-rest-in-groovy.html)

However it does not recognize
import groovyx.net.http.RESTClient
. You can try testing it in the groovy web sonsole provided and you will get the error.

I tryied
import groovyx.net.http.RESTClient.*
but still no success.

Any ideas are much appreciated.

Thank you in advance,
Liviu

Answer

Here is a simple Groovy script that sends an HTTP POST to an online server and parses the response with JsonSlurper.

This script can run as standalone on your machine; it probably won't work in an online Groovy REPL. It uses the Apache HTTPClient jar, which is added to the classpath via @Grab.

For a project, one would not use this method but rather add the jar to the classpath in Gradle.

Comments