How to use sendHttpPostRequest with spaces in url?

I want to send a HTTP request to a web server.

If I use

sendHttpPostRequest("http://localhost/web/message?text=Text_of_message&type=2&timeout=5")

it is working

sendHttpPostRequest("http://localhost/web/message?text=Text of message&type=2&timeout=5")

this one not.

Error message:

2018-01-18 15:54:06.173 [ERROR] [ntime.internal.engine.RuleEngineImpl] - Rule 'Werte initial setzen': Illegal character in query at index 38: http://localhost/web/message?text=Text in Message&type=2&timeout=5

How to escape spaces in url?

just a guess into the blue %20 for spaces? like Text%20of%20message

https://www.w3schools.com/tags/ref_urlencode.asp

I’ve tried it, but at the end the web server received %20 insted of blank

POST /web/message?text=Text%20in%20Message&type=2&timeout=5 HTTP/1.1

just edited my post above with a link. what about + character?

same, will received as +

POST /web/message?text=Text+in+Message&type=2&timeout=5 HTTP/1.1

I think the probem is not the receiving part, it is the function sendHttpPostRequest in combination with OH action.

seems so. then I can’t help :-/

What about this?

At beginning of rule

import java.net.URLEncoder

Then

val String request = "http://localhost/web/message?text=Text of message&type=2&timeout=5"
sendHttpPostRequest(URLEncoder::encode(request))

or

val String request = "http://localhost/web/message?text=Text of message&type=2&timeout=5"
sendHttpPostRequest(URLEncoder::encode(request, "ISO-8859-1"))

not working but different error message:

2018-01-19 13:02:39.334 [ERROR] [ntime.internal.engine.RuleEngineImpl] - Rule 'Werte initial setzen': Invalid URI host: null (authority: null)

I think the string is converted wrong to

http%3A%2F%2Flocalhost%2Fweb%2Fmessage%3Ftext%3DText+of+message%26type%3D2%26timeout%3D5

with the Exec Binding you must set @@ for spaces … perhaps this works for the sendHttpPostRequest too?

If not, you can give a BashScript a try … :wink:

Create script.sh

#!/bin/bash
curl http://localhost/web/message?text=Text of message&type=2&timeout=5

ExecuteCommandLine in rule

executeCommandLine("/etc/openhab2/scripts/script.sh")

if you have more than one Url Request… make a switch case in BashScript

#!/bin/bash

case $1 in
    1)
        curl http://localhost/web/message?text=FIRST Text of message&type=2&timeout=5
        ;;
    2)
        curl http://localhost/web/message?text=SECOND Text of message&type=2&timeout=5
        ;;
    *)
        echo "Kommando nicht vorhanden!"
        ;;
esac
executeCommandLine("/etc/openhab2/scripts/script.sh 1")
executeCommandLine("/etc/openhab2/scripts/script.sh 2")
1 Like