REST HTTP Client

Last modified by Jean SIMARD on 2021/03/18 11:28

application_osx_terminalREST client written in groovy
TypeSnippet
Category
Developed by

xwiki:XWiki.lux

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Description

xwiki has a set of REST APIs to expose wiki contents, however it is also possible to consume other RESTful resources. 

Suppose we have an xml resource that we want to use at http://localhost/users/18278273.xml which provides this xml

<?xml version="1.0" encoding="UTF-8"?>
<user>
 <id type="integer">995791683</id>
 <login>Lane</login>
 <email>[email protected]</email>
</user>

Example 1: Using HTTP URL Connection and Groovy XML Slurper

Here is a simple HTTP client to consume the above resource. What this does is connect a URL, parse the xml response, and display the results on an xwiki page.

{{groovy}}

 //Setup a connection to pull data in with REST
 def url = new URL("http://localhost/users/18278273.xml")
 def connection = url.openConnection()
 connection.setRequestMethod("GET")
 connection.connect()
 def returnMessage = ""

 if (connection.responseCode == 200 || connection.responseCode == 201){
   returnMessage = connection.content.text

   //print out the full response
   println returnMessage

   //parse the xml response
   def records = new XmlParser().parseText(returnMessage)
   println "id " + records.id.text()
   println "login " + records.login.text()
   println "email " + records.email.text()
  } else {
   println "Error Connecting to " + url
  }
{{/groovy}}

Make sure to change the URL to one of your choosing. You can also change the setRequestMethod to POST, PUT or DELETE. There is info on how to do more a complex xml parse with groovy here: http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlParser 

So now we have a fully restful http client which can be embedded on any page in xwiki. This is pretty cool, because now we could, for instance, make a twitter client with the twitter rest api and embed it on a page.

Example 2: Using Groovy's HTTP Builder

See http://groovy.codehaus.org/modules/http-builder/doc/get.html and http://groovy.codehaus.org/modules/http-builder/doc/xml.html

Also see this example of Nexus Integration that demonstrates the technique

Example 3: Using Groovy's REST Client

See this example of GitHub Integration that demonstrates the technique for accessing some REST resource using the JSON format.

Get Connected