Need help with httpget

I am trying to get data from http://www.openuv.io but I just can't get it to work.

def token = "x-access-token: ${key}"
	
	def params = [
		uri: "https://api.openuv.io/api/v1/uv?lat=${lat}&lng=${lng}",
		headers: ["x-access-token: ${token}"
		  ]
]
 httpGet(params) { response ->
        log.debug "Request was successful, $response.status"
        
         response.headers.each {
           log.debug "${it.name} : ${it.value}"
        }
}

It throws

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map on line 101 (refresh)

(Line 101 is the one starting with httpget(params))

I've tested in a lot of different ways but I had no luck so far. Can somebody point me in the right direction? Thanks.

Would this work for you??

httpGet("https://api.openuv.io/api/v1/uv?lat=${lat}&lng=${lng}?access_token= ${key}")

Nope. But thanks anyway!

groovyx.net.http.HttpResponseException: Forbidden on line 101 (refresh)

According to the API reference on openuv the API key are supposed to be in the header. I have tried to remove the header just to see what will happen, but I still got error.

To authorise your client just add your API Key xxxxxxxxxxxxxxxxxxxxxxxxxx to "x-access-token" header for each request.

You have to declare the headers as a map. Try this:

headers: [ 'x-access-token' : token ]
1 Like

Thank you! Now it finally works!

Working code:

	def params = [
	uri: "https://api.openuv.io/api/v1/uv?lat=${lat}&lng=${lng}",
	headers: [ 'x-access-token' : key ]
]
httpGet(params) { response ->
        log.debug "Request was successful, $response.status"
    
     response.headers.each {
       log.debug "${it.name} : ${it.value}"
    }}
1 Like

You might want to consider Async.

	def params = [
	uri: "https://api.openuv.io/api/v1/uv?lat=${lat}&lng=${lng}",
	headers: [ 'x-access-token' : key ]
	]
asynchttpGet("asyncHTTPHandler", params)
}

def asyncHTTPHandler(response, data) {
        log.debug "Request was successful, $response.status"
    
     response.headers.each {
       log.debug "${it.name} : ${it.value}"
    }}

Async allows the hub to be doing something else during that second or two that the website takes to respond. Of course, it's even more advantageous when the website is down for maintenance. :slight_smile:

2 Likes

Thank you for the tip! :smiley:

Weird thing. response.data returns:
{"result":{"uv":0,"uv_time":"2021-04-26T18:55:43.988Z","uv_max":3.3945,"uv_max_time":"2021-04-26T11:05:47.055Z","ozone":453.6,"ozone_time":"2021-04-26T18:04:04.915Z","safe_exposure_time":{"st1":null,"st2":null,"st3":null,"st4":null,"st5":null,"st6":null},"sun_info":{"sun_times":{"solarNoon":"2021-04-26T11:05:47.055Z","nadir":"2021-04-25T23:05:47.055Z","sunrise":"2021-04-26T03:36:02.718Z","sunset":"2021-04-26T18:35:31.392Z","sunriseEnd":"2021-04-26T03:40:15.223Z","sunsetStart":"2021-04-26T18:31:18.888Z","dawn":"2021-04-26T02:53:17.460Z","dusk":"2021-04-26T19:18:16.650Z","nauticalDawn":"2021-04-26T01:56:17.438Z","nauticalDusk":"2021-04-26T20:15:16.673Z","nightEnd":"2021-04-26T00:37:31.331Z","night":"2021-04-26T21:34:02.779Z","goldenHourEnd":"2021-04-26T04:28:07.686Z","goldenHour":"2021-04-26T17:43:26.425Z"},"sun_position":{"azimuth":2.102067757036459,"altitude":-0.058068533205527816}}}}

Exactly the same as with httpget. But when i use httpget I can print for example "response.data.result.uv" to the log. With asynchttpGet trying to do the same throws:

"groovy.lang.MissingPropertyException: No such property: result for class: java.lang.String on line 105 (asyncHTTPHandler)

	def params = [
uri: "https://api.openuv.io/api/v1/uv?lat=${lat}&lng=${lng}",
headers: [ 'x-access-token' : key ]
]
asynchttpGet("asyncHTTPHandler", params)
}


def asyncHTTPHandler(response, data) {
        log.debug "Request was successful, $response.status"
	log.debug response.data
    	log.debug response.data.result.uv

}

Weird since log.debug response.data returns exactly the same..

I had a similar problem and had to run the return data through a JSON Parser, so something like:

respData = parseJson(response.data)
log.debug respData.result.uv
JSON Parser
// Begin JSON Parser

def getNearestEnd(String json, int start, String head, String tail) {
    def end = start
    def count = 1
    while (count > 0) {
        end++
        def c = json.charAt(end)
        if (c == head) {
            count++
        } else if (c == tail) {
            count--
        }
    }
    return end;
}

//  Parse JSON Object
def parseObject(String json) {
    def map = [:]
    def length = json.length()
    def index = 1
    def state = 'none' // none, string-value, other-value
    def key = ''
    while (index < length -1) {
        def c = json.charAt(index)
        switch(c) {
            case '"':
                if (state == 'none') {
                    def keyStart = index + 1;
                    def keyEnd = keyStart;
                    while (json.charAt(keyEnd) != '"') {
                        keyEnd++
                    }
                    index = keyEnd
                    def keyValue = json[keyStart .. keyEnd - 1]
                    key = keyValue
                } else if (state == 'value') {
                    def stringStart = index + 1;
                    def stringEnd = stringStart;
                    while (json.charAt(stringEnd) != '"') {
                        stringEnd++
                    }
                    index = stringEnd
                    def stringValue = json[stringStart .. stringEnd - 1]
                    map.put(key, stringValue)
                }
                break

            case '{':
                def objectStart = index
                def objectEnd = getNearestEnd json, index, '{', '}'
                def objectValue = json[objectStart .. objectEnd]
                map.put(key, parseObject(objectValue))
                index = objectEnd
                break

            case '[':
                def arrayStart = index
                def arrayEnd = getNearestEnd(json, index, '[', ']')
                def arrayValue = json[arrayStart .. arrayEnd]
                map.put(key, parseArray(arrayValue))
                index = arrayEnd
                break

            case ':':
                state = 'value'
                break

            case ',':
                state = 'none'
                key = ''
                break;

            case ["\n", "\t", "\r", " "]:
                break

            default:
                break
        }
        index++
    }

    return map
}

// Parse JSON Array
def parseArray(String json) {
    def list = []
    def length = json.length()
    def index = 1
    def state = 'none' // none, string-value, other-value
    while (index < length -1) {
        def c = json.charAt(index)
        switch(c) {
            case '"':
                def stringStart = index + 1;
                def stringEnd = stringStart;
                while (json.charAt(stringEnd) != '"') {
                    stringEnd++
                }
                def stringValue = json[stringStart .. stringEnd - 1]
                list.add(stringValue)
                index = stringEnd
                break

            case '{':
                def objectStart = index
                def objectEnd = getNearestEnd(json, index, '{', '}')
                def objectValue = json[objectStart .. objectEnd]
                list.add(parseObject(objectValue))
                index = objectEnd
                break

            case '[':
                def arrayStart = index
                def arrayEnd = getNearestEnd(json, index, '[', ']')
                def arrayValue = json[arrayStart .. arrayEnd]
                list.add(parseArray(arrayValue))
                index = arrayEnd
                break

            case ["\n", "\t", "\r", " "]:
                break

            case ',':
                state = 'none'
                key = ''
                break;

            default:
                break
        }
        index++
    }

    return list
}

//  Parse the JSON - can be Object or Array
def parseJson(String json) {
    def start = json[0]
    if (start == '[') {
        return parseArray(json)
    } else if (start == '{') {
        return parseObject(json)
    } else {
        return null
    }
}

//End JSON Parser
3 Likes

I use JsonSlurper, as shown here: JsonSlurper (groovy 2.4.0 API)

2 Likes

Download the Hubitat app