Integrating Web Services

From bemoko developer wiki

Jump to: navigation, search

Overview

Integrating with Web Services of various flavours is made simple in bemokoLive, let's have a look at a quick example ...

Web Service Example

Define a class which contains your core integration points with the web service, for example with XML over HTTP you might want to use something like the following:

import groovy.xml.StreamingMarkupBuilder
 
class WebServiceRequestLogin extends WebServiceRequest {
  def builder=new StreamingMarkupBuilder()
  def result
  def password
  def username
 
  public WebServiceRequestLogin(String username,String password) {
    this.username=username
    this.password=password
  }
 
  public boolean send() {
    result=makeRemoteCall()
    def responseCode=Integer.parseInt(response.header.responseCode[0].text())
    if (responseCode!=REMOTE_OK) {
      /*
       * Handle login failure
       */  
       ....
    } else {	
      /*
       * Handle successful login
       */  
      ....
    }  
  }
 
  def makeRemoteCall() {
    def conn = new URL(ENDPOINT).openConnection()
    conn.requestMethod="POST"
    conn.doOutput=true
    conn.outputStream.withWriter("ASCII") {
      it << builder.bind( 
         {
           webservice {
             request {
               method("login")
               username(username)
               password(password)
             }
           }
	})
    }
    if (conn.responseCode == conn.HTTP_OK) {	
      return (new XmlParser()).parseText(conn.inputStream)
    }
    throw new GroovyRuntimeException("Request failed : $conn.responseCode")
  }
}

This will send an XML request such as

<webservice>
  <request>
   <method>login</method>
   <username>myusername</username>
   <password>mypassword</password>
  </request>
</webservice>

Within your plugin you can call this login web service call with something like:

def request=new WebServiceRequestLogin(parameters.username,parameters.password);
if (request.send()) {
  /*
   * Handle success
   */
  ...
} else {
  /*
   * Handle failure
   */
   ...
}