URL-decode a string in Common Lisp
Asked Answered
E

2

6

I have a string that contains an escaped URL:

http%3A%2F%2Fexample.com%3Ffoo%3Dbar+baz

I'm trying to decode it to the following:

http://example.com?foo=bar+baz

However, I can't find any suitable function exported by Drakma. I can encode like so:

* url-string

"http://example.com?foo=bar+baz"
* (drakma:url-encode url-string :utf-8)

"http%3A%2F%2Fexample.com%3Ffoo%3Dbar%2Bbaz"

... so I figure I'm on the right track. If anyone could supply a nudge in the right direction I'd appreciate it :-) I'm using SBCL 1.0.54, built from source on 64-bit Linux Mint 13.

If it helps clarify what I'm trying to do, in Ruby, I'd do the following:

> uri_string = "http%3A%2F%2Fexample.com%3Ffoo%3Dbar+baz"
 => "http%3A%2F%2Fexample.com%3Ffoo%3Dbar+baz" 
> URI.decode uri_string
 => "http://example.com?foo=bar+baz" 
Evanesce answered 2/7, 2012 at 11:48 Comment(2)
In case you're wondering, I know it's decidedly weird that the entire URL is escaped, including the protocol specification. I'm trying to write a cross-platform download client for an Australian online music store that provides files containing lists of entirely-escaped URLs like the example above.Evanesce
just asking the obvious: (apropos "DECODE") does not show any interesting function? (apropos "DECODE" "DRAKMA") ?Ashur
A
15

A quick SLIME session.

CL-USER> (ql-dist:system-apropos "url")

#<SYSTEM curly / curly-20120407-git / quicklisp 2012-05-20>
#<SYSTEM curly.test / curly-20120407-git / quicklisp 2012-05-20>
#<SYSTEM do-urlencode / do-urlencode-20120407-git / quicklisp 2012-05-20>
#<SYSTEM url-rewrite / url-rewrite-0.1.1 / quicklisp 2012-05-20>

CL-USER> (ql:quickload :do-urlencode)

C-cC-dpdo-urlencodeRET

DO-URLENCODE:URLDECODE
  Function: (not documented)
DO-URLENCODE:URLENCODE
  Function: (not documented)
DO-URLENCODE:URLENCODE-MALFORMED-STRING
  Type: (not documented)
DO-URLENCODE:URLENCODE-MALFORMED-STRING-STRING
  Generic Function: (not documented)

CL-USER> (do-urlencode:urldecode "http%3A%2F%2Fexample.com%3Ffoo%3Dbar%2Bbaz")

"http://example.com?foo=bar+baz"
Amuse answered 2/7, 2012 at 15:27 Comment(1)
Thanks :-) I'm still learning the 'Lisp way' of doing things ... it never even crossed my mind that there might be a way of getting help on Quicklisp packages from the REPL.Evanesce
C
5

Found another solution, with Quri, a uri handling library with encoding and decoding utilities (for uri and parameters):

(url-decode "http%3A%2F%2Fexample.com%3Ffoo%3Dbar%2Bbaz")
;; "http://example.com?foo=bar+baz"

To install with (ql:quickload :quri) and then optionaly (use-package :quri).

(my sources: lisp-lang.org's recommend libraries and awesone-cl).

Cicisbeo answered 31/1, 2017 at 1:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.