How can I make HTTP request with HttpBuilder in the new scripting environment?
-
Hello,
I need to make an HTTP post request in a Script Event Handler. But I keep getting errors when using HttpBuilder.
At first I got the error: ReferenceError: HttpBuilder is not defined
Then I defined the HttpBuilder as :
const HttpBuilder = Java.type('com.serotonin.m2m2.rt.script.HttpBuilderScriptUtility');
Now I'm getting the error: TypeError: invokeMember (request) on com.serotonin.m2m2.rt.script.HttpBuilderScriptUtility failed due to: Unknown identifier: request
What am I missing here?
-
@mert I will need to see the entire script to help you out. Also what script engine are you using Graal.js or Nashorn?
-
@terrypacker I'm using Graal.js. Here is the script :
const HttpBuilder = Java.type('com.serotonin.m2m2.rt.script.HttpBuilderScriptUtility'); HttpBuilder.request({ path: url, method: "POST", headers: { ContentType : "application/json", Authorization : "Basic "+token, }, content: JSON.stringify({ "type": 0, "message": "This is a test message" }), err: function(status, headers, content) { //errorCallback throw "Request got bad response: " + status + content; }, resp: function(status, headers, content) { //responseCallback console.log(content) return true; }, excp: function(exception) { //exceptionCallback throw exception.getMessage(); } });
-
@mert thanks. I suggest you avoid the "Script Utility" classes when using the new javascript environment, they were specifically designed for the legacy engine and context and will probably be more confusing to use than directly using the underlying Apache http client library.
I coded up an example using the library here:
https://github.com/infiniteautomation/script-examples/blob/main/httpGetRequest.jsFor reference I used this java code as my template to port into javascript:
https://github.com/infiniteautomation/ma-modules-contrib/blob/main/system-settings-ds/src/com/infiniteautomation/mango/systemSettings/rt/SystemSettingsDataSourceRT.javaThere is a lot more you can do with this client, my example is pretty basic but will give you a starting point.
-
@terrypacker thanks a lot, an example code is more than enough. I will look into the library in detail and see how to use it in the upcoming days.
Thanks once again!