1 year ago

#375573

test-img

hermit.crab

Building a curl command with parameters that have to be URL-encoded

I want to send data to a server via curl. The script has to first build the curl command by appending several parameters. Something like this:

# set other params...

param4_name="param4"
param4_value="Hello world"

params=""

# append other params to $params...

if [[ ! -z "$param4_value" ]]; then
    params="$params --data-urlencode \"$param4_name=$param4_value\" "
fi

response="$(curl \
    $params \
    --get \
    $my_url/test)"

When I use this code, however, the server receives the curl request as:

HTTP-Request: GET /test?"param4=Hello HTTP/1.1

(The " is included in the key and " world" is missing in the value.)

If I adjust the code to use:

if [[ ! -z "$param4_value" ]]; then
    params="$params --data-urlencode $param4_name="$param4_value" "
fi

The server receives this:

HTTP-Request: GET /test?param4=Hello HTTP/1.1

(" world" is missing in the value.)

How do I adjust the bash code so that the server receives this request instead:

HTTP-Request: GET /test?param4=Hello%20World HTTP/1.1

I'm amenable to using this solution. But is there a "neater" way to do this without resorting to using a function, an embedded curl call, or perl/sed/awk/etc?

bash

curl

urlencode

0 Answers

Your Answer

Accepted video resources