156

I have some url which has space in it's query param. I want to use this in curl, e.g.

curl -G "http://localhost:30001/data?zip=47401&utc_begin=2013-8-1 00:00:00&utc_end=2013-8-2 00:00:00&country_code=USA"

which gives out

Malformed Request-Line

As per my understanding o/p is due to the space present in query param.

Is there any away to encode the url automatically before providing it to curl command?

Aashish P.
  • 1,561
  • 2
  • 10
  • 3

2 Answers2

249

curl supports url-encoding internally with --data-urlencode:

$ curl -G -v "http://localhost:30001/data" --data-urlencode "msg=hello world" --data-urlencode "msg2=hello world2"

-G is also necessary to append the data to the URL.

Trace headers

> GET /data?msg=hello%20world&msg2=hello%20world2 HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu)
> Host: localhost
> Accept: */*
kevinarpe
  • 667
  • 6
  • 14
damphat
  • 3,234
  • 1
  • 13
  • 8
5
 curl -G "$( echo "$URL" | sed 's/ /%20/g' )"

Where $URL is the url you want to do the translations on.

There are also more than one type of translation (encoding) you can have in a URL, so you may want to do:

curl -G "$(perl -MURI::Escape -e 'print uri_escape shift, , q{^A-Za-z0-9\-._~/:}' -- "$URL")"

instead.

ctrl-alt-delor
  • 27,473
  • 9
  • 58
  • 102
Drav Sloan
  • 14,145
  • 4
  • 45
  • 43