Making request from script Mapper

Hi all, I am trying to write a script mapper. I need to hit my Backend to verify some stuff. I am unable to do so. Is there any best solution to achieve such kind of thing??

var url = 'http://some-url.com';
fetch(url, {
  method: "GET",
  headers: {"Content-type": "application/json;charset=UTF-8"}
})
.then(response => {
	var json = JSON.parse(response); 
    var temp = json.id;
    
});

I am trying this code but getting error while saving script.

Hi,

You cannot use server-side nashorn Javascript like you would do it in a browser. Instead, there is the Java class library you have access to:

https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/package-summary.html
https://javaee.github.io/javaee-spec/javadocs/javax/json/Json.html

URI = Java.type("java.net.URI");
HttpClient = Java.type("java.net.http.HttpClient");
HttpRequest = Java.type("java.net.http.HttpRequest");
BodyHandlers = Java.type("java.net.http.HttpResponse.BodyHandlers");
StringReader = Java.type("java.io.StringReader");
Json = Java.type("javax.json.Json");

var url = "http://some-url.com";
var httpClient = HttpClient.newBuilder()
	.build();
var httpRequest = HttpRequest.newBuilder()
	.uri(URI.create(url))
	.header("Content-Type", "application/json; charset=UTF-8")
	.GET()
	.build();
var response = httpClient.send(httpRequest, BodyHandlers.ofString());
var jsonReader = Json.createReader(new StringReader(response.body()));
var jsonObj = jsonReader.readObject();
jsonReader.close();
var temp = jsonObj.getString("id", "");

I use similar code in mappers and authenticators (Keycloak 17 (Wildfly version), OpenJDK 11).

Regards,
Matthias

1 Like

Thank you for the help. so could we debug this code at some point. I have deployed JAR file

Sorry, I forgot an important line in my code, copy paste errors…:

var httpClient = HttpClient.newBuilder()
	.build();

Caused by: java.lang.ClassNotFoundException: java.net.http.HttpClient from [Module "org.keycloak.keycloak-services" version 15.0.2.redhat-00001 from local module loader

Getting this error while hitting the script mapper

java.net.http.HttpClient is included in Java 11 or newer. Are you running an older JDK?
I am using this in mappers and authenticators since 2 years (Keycloak 10+, always Ubuntu 18/20 with OpenJDK 11, always Keycloak Wildfly distribution, never used docker…)

1 Like

Yes it may be version issue. I am using OpenJdk8. updating this to 11.

Thanks alot for the help @mbonn. I am able to achieve things that are needed. I have update keycloak version to 11 and it worked. :slight_smile: