Sunday, October 28, 2012

Posting XML request using Groovy's HttpBuilder


       

Here I would like discuss few points on how to use HttpBuilder to post xml request message onto service url.

       /**
        * Creates a User based on params.
        *
        * @param params
        * @return
        */
       def submitMessage(Map params) {
             
              def http =  HttpBuilder();
              http.post(buildRequestMap(params, buildRequestXML), processScccess);
       }
      
      
       /**
        * Method to create properties map to post over the HTTP.
        * @param reqParams
        * @param reqCreatorClosure
        * @return
        */
       Map buildRequestMap(Map reqParams, Closure reqCreatorClosure) {

              Map options = [:];
              Map h = [:];

              h.'Content-Type' = 'text/xml';
              options.'headers' = h;
              options.'uri' = "http://localhost/test/processServlet";
             
              if(null != reqCreatorClosure) {
                     Object returnVal = reqCreatorClosure.call(reqParams);
                     options.put("body", returnVal);
              }
              return options;
       }

      
       /**
        * Closure to create a request xml based on params
        */
       def buildRequestXML = { Map params ->
             
              def writer = new StringWriter()
              def xml = new MarkupBuilder(writer)
              xml.request() {
                     message(messageId: "test123") {
                        "Test Message"
                     }
              }
              return writer.toString();
       }
      
       /**
        * Closure the process a successful response.
        */
       def processScccess = { resp, xml ->
              println "My response handler got response: ${resp.statusLine}"
              println "Response = ${xml}" // print response reader
       }

Thank you..