cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - New to the community? Learn how to post a question and get help from PTC and industry experts! X

Accessing the Body of a Post Request in a Groovy Script

No ratings

Since the advent of 6.1.6 we've been able to access the body of a post in a Groovy script.  This frees us from the tyranny of those pesky predefined parameters and opens up all sorts of Javascript object-passing possibilities.

To keep this example as simple as possible, there are only two files:

  1. postbody.html
  2. TestPostBody.groovy

postbody.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

            "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

    <title>Scripto Post Body Demo</title>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

    <meta name="apple-mobile-web-app-capable" content="yes"/>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta http-equiv="refresh" content="3600">

</head>

<body>

<div id="wrapper">

<div id="header">

<h1>Scripto Post Body Demo</h1>

</div>

<p>

Username:<input type="text" id="username" /><br />

Password:<input type="password" id="password"  /><br /><br />

Enter some valid JSON (validate it <a href="http://jsonlint.com/" alt="jsonlint">here</a> if you're not sure): <br /><textarea id="jsoninput" rows=10 cols=20></textarea><br />

Enter arbitrary Text: <br /><textarea id="textinput" rows=10 cols=20></textarea>

<input type="submit" value="Go" id="submitbtn"  onclick="poststuff();"/>

</p>

<div id="response"></div>

</div>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>

  <script type="text/javascript">

        var poststuff= function(){

            var data = {}

            var temp

            if ($("#jsoninput").val() != ""){

                try {

                    temp = $.parseJSON($("#jsoninput").val())

                }

                catch (e){

                    temp = ""

                }

                if (temp && temp != ""){

                    data = JSON.stringify(temp)

                }

            }

            else if ($("#textinput").val() != ""){

                data.text = $("#textinput").val()

                data = JSON.stringify(data)

            }

            else data = {"testing":"hello"}

            if ($("#username").val() != "" && $("#password").val() != ""){

                // you need contentType in order for the POST to succeed

                var promise = $.ajax({

                    type:"POST",

                    url: "http://dev6.axeda.com/services/v1/rest/Scripto/execute/TestPostBody?username=" + $("#username").val() + "&password=" + $("#password").val(),

                    data: data,

                    contentType:"application/json; charset=utf-8",

                    dataType:"text"

                })

                $.when(promise).then(function(json){

                    $("#response").html("<p>" + JSON.stringify(json) + "</p><br />Check your console for the object.<br />")

                    console.log($.parseJSON(json))

                    $("#jsoninput").val("")

                    $("#textinput").val("")

                })

            }

        }

</script>

</body>

</html>

TestPostBody.groovy

import net.sf.json.JSONObject

import groovy.json.JsonSlurper

import static com.axeda.drm.sdk.scripto.Request.*;

try {

    // just get the string body content

    response = [body: body]

    response.element = []

    // parse the text into a JSON Object or JSONArray suitable for traversing in Groovy

    // this assumes the body is stringified JSON

    def slurper = new JsonSlurper()

    def result = slurper.parseText(body)

    result.each{ response.element << it }

} catch (Exception e) {

    response = [

                faultcode: 'Groovy Exception',

                faultstring: e.message

            ];

}

return ["Content-Type": "application/json","Content":JSONObject.fromObject(response).toString(2)]

The "body" variable is passed in as a standalone implicit object of type String.  The key here is that to process the string as a Json object in Groovy, we send stringed JSON from the Javascript, rather than the straight JSON object.

FYI: If you happen to be using Scripto Editor, you might like to know that importing the Request class disables the sidebar input of parameters.  You can enter the parameters in the sidebar, but if this import is included the parameters will not be visible to the script.

To access the POST body through the Request Object, you can also refer to: Using Axeda Scripto

Version history
Last update:
‎May 10, 2016 12:04 PM
Updated by:
Labels (1)