[JavaScript] Syntax to insert API Token into SendHTTPGetRequest

I’m struggeling with incooperating an API Token into a sendHTTPGetRequest.
Using BasicAuth it works like this:

var return = HTTP.sendHttpGetRequest("http://user:password@", 10000);

According to the HTTP Action-docs using DSL it should work like this:

val headers = newHashMap("Cache-control" -> "no-cache")
val output = sendHttpGetRequest("https://example.com/?id=1", headers, 1000)

Howto convert that (especially the headers) to JavaScript?

I don’t know if it’s the same…I use this headers variable with sendHttpPutRequest and it’s working with OH Api, replace “MyToken” with your actual token.

        val headers = newHashMap("Authorization" -> "Bearer MyToken", "WWW-Authenticate"-> "Basic")

I don’t know if it’s working in javascript too…but maybe could give you some hint.

Thanks for the repsonse, however JavaScript is struggeling exactly with that line.

var headers = newHashMap("Authorization" -> "Bearer oh.MyToken.qwertz");

Error: Expected an operand but found > pointing to the > character.

If newHashMap it’s the dsl way to create an array…maybe it’s enough to create an array in a javascript way:

var headers = [];
headers["Authorization"] = "Bearer MyToken";
headers["WWW-Authenticate"] =  "Basic";

Worth a try :wink:

1 Like

Just to add a little bit of explanation and correct some terminology.

  • newHasMap is a Rules DSL thing. It doesn’t exist in any of the other languages. It’s just a shorthand for new HashMap<Object,Object>().

  • The object created by newHashMap is a java.util.HashMap. That’s right, it’s a Java HashMap, not something native to Rules DSL.

  • A HashMap is not an array. It might be a quibble but there is an important distinction in programming between a map and an array. A map has N values that are accessed/indexed by a key. The key can be almost anything, a string, number, etc. An array has N values and can only be accessed by a numerical index. If you want the fifth element you’d use myarray[4]. Note, Rules DSL does not support the creation of arrays, but you can use a java.util.ArrrayList instead. That’s why when you have a List (e.g. MyGroup.members) you can’t use [4] to access the elements and have to use .get(4).

  • Another name for a map is a dict. And that is what you’ve shown how to create in JavaScript, a native JavaScript dict. See JavaScript Arrays for how to create JavaScript Arrays. But you could create a java.util.HashMap too if you wanted even in the JavaScript.


Thank you for the explanation :+1:

I was imprecise indeed…I’m not familiar with java/javascript terminology, I come from PHP where you just call them array…or “associative array” when you want to be accurate :smiley:

Indeed, associative array is another name for a map/dict.