groovyhttpbuilder

HTTPBuilder & Session ID


I have the following code to connect to a REST API service, authenticate, retrieve a session ID then make further requests passing the session ID to authenticate. The initial request works and I get a HTTP 200 OK plus the session ID in the response, however when I try to make a second request passing the session ID in the header, I get

Caught: groovyx.net.http.HttpResponseException: Bad Request

I know the script can be written much better with the use of classes and try / catch etc. I am still learning both java and groovy so I start by just trying to do everything within the same class.

Any help much appreciated.

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.URIBuilder
import static groovyx.net.http.Method.POST
import static groovyx.net.http.ContentType.*

def url = 'https://1.1.1.1/web_api/'
def uri = new URIBuilder(url)

String CHKPsid

uri.path = 'login'
def http = new HTTPBuilder(uri)
http.ignoreSSLIssues()


http.request(POST,JSON ) { req ->
headers.'Content-Type' = 'application/json'
body = [
        "user":"username",
        "password":"password"
]
    response.success = { resp, json ->
        println (json)
        CHKPsid = (json.sid)
        println "POST Success: ${resp.statusLine}"
    }
}

uri.path = 'show-changes'
http.request(POST,JSON ) { req ->
headers.'Content-Type' = 'application/json'
headers.'X-chkp-sid' = '${CHKPsid}'
body = [
        "from-date"   : "2017-02-01T08:20:50",
        "to-date"     : "2017-10-21"
  ]
    response.success = { resp, json ->
        println (json)
        println "POST Success: ${resp.statusLine}"
  }
}

Solution

  • String interpolation does not work with single (or triple single quotes). When groovy will evaluate '${CHKPsid}' (single quotes), its value will be ${CHKPsid} (this string). In order to use the value of the variable, you should use double quotes: "${CHKPsid}" or simply just the variable: headers.'X-chkp-sid' = CHKPsid.

    So the output of this:

    String CHKPsid = "abc123"
    println '${CHKPsid}'
    println "${CHKPsid}"
    

    will be:

    ${CHKPsid}
    abc123
    

    In order to quickly test what the server receives, you can use httpbin.org or requestb.in