Abstract

This code snippet makes an HTTP call and processes the returned data.

Logic

Snippet 

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.<methodName>
import static groovyx.net.http.ContentType.<contentType>
 
// initialize a new builder and give a default URL
def http = new HTTPBuilder("<URL>")
 
def data = http.request(<methodName>,<contentType>) { req ->
 
  response.success = { resp, reader ->
    assert resp.status == 200
	return reader
  }
 
  // called only for a 404 (not found) status code:
  response."404" = { resp ->
    log.error ("Not found")
  }
}

if (data) {
  // process returned data
}
Placeholders

Placeholder

Description

Example

<URL>

URL

https://www.google.com/

<methodName>

Name of the request method

GET

<contentType>

Type of the content requested for

TEXT

Context

The outcome of the code snippet depends on the content type passed to the request method. You could use this code, for example, to get a specific currency conversion rate.

Example

To get the HTML text an issue view page, you can use this snippet to make the HTTP call, get the content and parse it.

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.TEXT
 
// initialize a new builder and give a default URL
def http = new HTTPBuilder("https://www.google.com/")
 
return http.request(GET,TEXT) { req ->
  response.success = { resp, htmlText ->
    assert resp.status == 200
    log.debug("My response handler got response: ${resp.statusLine}")
    if(htmlText){
     return htmlText.getText()
    }
    else{
      return null
    }
  }
 
  // called only for a 404 (not found) status code:
  response."404" = { resp ->
    log.error ("Not found")
    return null
  }
}

Reference

Related articles