HttpUtil

The HttpUtil class provides a set of methods for making HTTP requests, including GET, POST, HEAD, PUT, DELETE, PATCH, and OPTIONS, allowing you to interact with web services and retrieve or send data over the internet. It offers a convenient and flexible way to work with HTTP requests in your applications.

Methods

get(url: String): Makes an HTTP GET request to the specified URL.

var getRequest = HttpUtil.get("https://example.com/api/data");

head(url: String): Performs an HTTP HEAD request to the given URL.

var headRequest = HttpUtil.head("https://example.com/api/resource");

options(url: String): Sends an HTTP OPTIONS request to the provided URL.

var optionsRequest = HttpUtil.options("https://example.com/api/info");

post(url: String): Executes an HTTP POST request to the specified URL.

var postRequest = HttpUtil.post("https://example.com/api/create");

delete(url: String): Sends an HTTP DELETE request to the specified URL.

var deleteRequest = HttpUtil.delete("https://example.com/api/remove");

patch(url: String): Performs an HTTP PATCH request to the specified URL.

var patchRequest = HttpUtil.patch("https://example.com/api/modify");

put(url: String): Makes an HTTP PUT request to the specified URL.

var putRequest = HttpUtil.put("https://example.com/api/update");

HttpResponse Class

The HttpResponse class provides methods to retrieve information about an HTTP response. It offers methods to obtain the HTTP status code, the status text, response headers, and the response body, which can be of various types, such as strings or JSON objects. This class is essential for inspecting and working with the results of HTTP requests.

Methods

getStatus(): Integer: Retrieves the HTTP status code of the response.

var statusCode = response.getStatus();

getStatusText(): String: Retrieves the HTTP status text of the response.

var statusText = response.getStatusText();

getHeaders(): any: Retrieves the response headers as a map with the same case as the server response.

var responseHeaders = response.getHeaders();

getBody(): T: Retrieves the response body, which can be of various types.

var responseBody = response.getBody();

HttpRequest Class

The HttpRequest class represents an HTTP request and provides methods to convert the response body to different data types. It includes functions to retrieve the response as a string, JSON object, or binary data. HttpRequest is valuable for handling the content of HTTP responses.

Methods

asString(): HttpResponse<String>: Converts the response body to a string.

var stringResponse = request.asString();

asJson(): HttpResponse<JsonNode>: Parses the response body as JSON.

var jsonResponse = request.asJson();

asBinary(): HttpResponse<InputStream>: Retrieves the response body as binary data.

var binaryResponse = request.asBinary();

GetRequest Class

The GetRequest class includes methods for adding route parameters and request headers to a GET request. It also supports basic authentication, making it a versatile tool for customizing GET requests with specific requirements.

Methods

routeParam(name: String, value: String): Adds a route parameter to the request.

request.routeParam("id", "123");

header(name: String, value: String): Adds a request header.

request.header("Authorization", "Bearer token123");

basicAuth(username: String, password: String): Adds basic authentication credentials.

request.basicAuth("username", "password123");

HttpRequestWithBody Class

The HttpRequestWithBody class extends the capabilities of an HTTP request by allowing you to add route parameters, request headers, and basic authentication credentials. Additionally, it enables you to set the request body content. This class is particularly useful for configuring requests with additional data and parameters.

Methods

routeParam(name: String, value: String): Adds a route parameter to the request.

postRequest.routeParam("category", "books");

header(name: String, value: String): Adds a request header.

postRequest.header("Content-Type", "application/json");

basicAuth(username: String, password: String): Adds basic authentication credentials.

postRequest.basicAuth("user123", "password456");

body(body: String): Sets the request body content.

postRequest.body("{'name': 'John', 'age': 30}");

field(name: String, value: String): Adds a field to a multipart request.

postRequest.field("key", "value");

field(name: String, file: File): Adds a file field to a multipart request.

postRequest.field("image", new File("image.jpg"));

RequestBodyEntity Class

The RequestBodyEntity class focuses on setting the body content of an HTTP request. It's a valuable tool for customizing the content you send in an HTTP request.

Methods

body(body: String): Sets the request body content.

requestBodyEntity.body("{'name': 'Alice', 'email': 'alice@example.com'}");

MultipartBody Class

The MultipartBody class is designed for handling multipart requests, which are used for sending files and form data. It offers methods to add fields and file attachments to a multipart request. This class is essential for managing complex requests that include a combination of textual and binary data, such as file uploads.

Methods

field(name: String, value: String): Adds a field to a multipart request.

var multipartRequest = HttpUtil.post("https://example.com/upload");
multipartRequest.field("name", "Alice");
multipartRequest.field("email", "alice@example.com");

field(name: String, file: File): Adds a file field to a multipart request.

var multipartRequest = HttpUtil.post("https://example.com/upload");
multipartRequest.field("profile_picture", FileUtil.readFile("profile.jpg"));

Here's a complete example of a POST request with a file upload using MultipartBody:

// Define the file path to the PDF document you want to upload.
var filePath = "C:\\B2Win\\document.pdf";

// Read the content of the file from the given file path using FileUtil.
var file = FileUtil.readFile(filePath);

// Create a multipart HTTP POST request to the specified URL (https://example.com/upload).
var multipartRequest = HttpUtil.post("https://example.com/upload");

// Add a field named "description" with the description of the file.
multipartRequest.field("description", "A PDF document");

// Add the file as a field named "file" to the multipart request.
multipartRequest.field("file", file);

// Send the multipart request to the server and get the response as a string.
var response = multipartRequest.asString();

This example sets up a multipart request to upload a file along with some form fields.


Examples

Example: GET request from Exchanges Rate API

Retrieve and process exchange rate data from an external API, enabling further analysis or use.

// Send an HTTP GET request to the specified URL to retrieve exchange rate data.
var request = HttpUtil.get("https://boi.org.il/PublicApi/GetExchangeRates");

// Parse the response body, which is expected to be in JSON format.
var jsonContent = JsonUtil.parse(request.asString().getBody());

// Extract the 'exchangeRates' property from the JSON content
var exchanges = JsonUtil.stringify(jsonContent.exchangeRates);

// Create a temporary JSON file with the extracted exchange rate data.
return FileUtil.createTempFile("tmp.json", exchanges);

Example: GET request from Local API information

This script dynamically retrieves local API data, such as country and city, based on the IP address obtained from a variable or property.

// Set a variable to the API URL, with the IP being read from the Column IP
// or from another property value or static value as you choose.
var ip = '149.188.234.169'
var remoteApiUrl = 'http://ip-api.com/json/'+ip;

// Create a GET request to the url
var request = HttpUtil.get(remoteApiUrl);

// Get the body as a String and parse it into a Json Object
var data = JsonUtil.parse(request.asString().getBody());

// Parse the Json response and read the country and city
return data // return JSON object
return data.status // returns status, for example: 'success'
return data.country // returns API country, for example: 'USA'
// Data fields: status, country, countryCode, region, regionName, city, zip, lat,
// lon, timezone, isp , org, as, query

Example: Call a rest API with the IP address and return the country and city as string

//Set a variable to the API url, with the IP being read from the Column IP or from another property value or static value as you choose
var remoteApiUrl = 'http://ip-api.com/json/' + Col_ip + '?fields=status,country,city';

//Create a GET request to the url
var request = HttpUtil.get(remoteApiUrl);
0
//Get the body as a String and parse it into a Json Object
var data = JsonUtil.parse(request.asString().getBody());

//Parse the Json response and read the country and city
return data.get('country').asText() + ', '+ data.get('city').asText()

Example: POST request to a data publishing API

Prepares and sends a JSON payload to a data publishing API, and it checks the response status. If the status is 200, it indicates successful data publication; otherwise, it handles errors and provides the response code.

// Define the URL of the data publishing API
var apiUrl = "https://example.com/data-publish";

// Prepare the data to be sent (assuming it's in JSON format)
var dataToPublish = {
    "key1": "value1",
    "key2": "value2"
};

// Convert the data to a JSON string
var jsonData = JsonUtil.toJson(dataToPublish);

// Configure and send a POST request to the API
var response = HttpUtil.post(apiUrl)
    .header("Content-Type", "application/json")
    .body(jsonData)
    .asString();

// Check the response and handle it as needed
if (response.getStatus() == 200) {
    return ("Data published successfully.");
} else {
    return ("Error publishing data. Response code: " + response.getStatus());
}

Last updated