How to encode/decode a URL string in TMS WEB Core using Delphi?

70 views Asked by At

In my FireMonkey Apps, I can simply add the System.NetEncoding unit to my uses list and then use the TNetEncoding.URL.Encode() and TNetEncoding.URL.Decode() functions, but the System.NetEncoding isn't available in TMS WEB Core.

I've also tried the IdURI and HTTPApp units, but they're not available either.

Is there perhaps a TMS unit for encoding and decoding URLs in TMS WEB Core?

1

There are 1 answers

2
Ian Boyd On

Delphi has a long history full of timult dealing with Url encoding:

  • TIdURI.URLEncode(url) - buggy
  • HTTPApp.HttpEncode(url) - Deprecated in Delphi 10.3
  • TNetEncoding.URL.Encode(s) - buggy

And then Windows itself has a selection of functions:

If your FireMoney app is not running on Windows, then you might have to simply cave and roll your own.

Just be aware that a lot of implementations will say that the only valid characters in URLs are:

`A`..`Z`, `a`..`z`, `0`..`9`, `-`, `_`, `~`, `.`

and escape anything else. When in reality the following is a valid and allowed URL:

http://example.com/:@-.!$&'(),=;:@-._~!$&'()*,=:@-.!$&'(),==?/?:@-._~!$'()*,;=/?:@-._~!$'()*,;==#/?:@-._~!$&'()*,;=
\__/   \_________/\________________________________________/\__________________________________/\_________________/
 |         |                         |                                        |                          |
Scheme   Host                       Path                                    Query                    Fragment

And each of your different parts have different rules about what is allowed.

Part Value
Scheme http
Username
Password
Host example.com
Port 80
Path /:@-.!$&'(),=;:@-._~!$&'()*,=:@-.!$&'(),==
Query ?/?:@-._~!$'()*,;=/?:@-._~!$'()*,;==
Fragment #/?:@-._~!$&'()*,;=

What's more is that depending on your use case, maybe you want to urlencode the entire string:

  • Before: http://stackoverflow.com/
  • After: http%3A%2F%2Fstackoverflow.com%2F

When maybe in reality you only wanted it to escape "bad" urls:

  • Before: https://stackoverflow.com/terms of service
  • After: https://stackoverflow.com/terms%20of%20service

tl;dr: Try to use Windows.