Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I URL-escape a string in Mathematica?

For example,

urlesc["foo.cgi?abc=123"]

should return

foo.cgi%3Fabc%3D123

This is also known as percent-encoding.

Also, for better readability, spaces should encode to pluses. I believe that's always acceptable for URL escaping.

like image 805
dreeves Avatar asked Jul 01 '10 19:07

dreeves


2 Answers

Another method, using J/Link and java.net.URLEncoder:

In[116]:= Needs["JLink`"]; InstallJava[];
  LoadJavaClass["java.net.URLEncoder"];

In[118]:= URLEncoder`encode["foo.cgi?abc=123"]
Out[118]= "foo.cgi%3Fabc%3D123"

There's also java.net.URLDecoder for decoding.

like image 71
Michael Pilat Avatar answered Sep 30 '22 17:09

Michael Pilat


Here's my solution:

cat = StringJoin@@(ToString/@{##})&;         (* Like sprintf/strout in C/C++. *)
re = RegularExpression;

hex = IntegerString[#,16]&;        (* integer to hex, represented as a string *)
up = ToUpperCase;
asc = ToCharacterCode[#][[1]]&;                    (* character to ascii code *)
subst = StringReplace;

urlesc[s_String] := subst[s, {" "->"+", re@"[^\w\_\:\.]":>"%"<>up@hex@asc@"$0"}]
urlesc[x_] := urlesc@cat@x
unesc[s_String] := subst[s, re@"\\%(..)":>FromCharacterCode@FromDigits["$1",16]]

As a bonus, here's a function to encode a list of rules like {a->2, b->3} into GET parameters like a=2&b=3, with appropriate URL-encoding:

encode[c_] := cat @@ Riffle[cat[#1, "=", urlesc[#2]]& @@@ c, "&"]
like image 30
dreeves Avatar answered Sep 30 '22 17:09

dreeves