URLs and encodings
Addresses, query strings and Base64 look simple until a space or an ampersand arrives. This lesson takes a URL apart, builds and reads query strings safely, resolves relative addresses and encodes bytes as text.
What you will learn#
- the parts of a URL and the
Uriclass, - percent-encoding of special characters (
WebUtility.UrlEncode/UrlDecode), - building and reading a query string,
- combining a base address with a relative path,
- Base64, and why it is not encryption,
- checking that an address is valid.
The parts of a URL#
https://shop.example.com:8443/products/shoes?color=red&size=42#reviews
└scheme┘ └─────host─────┘└port┘└───path───┘ └──── query ────┘└fragment┘The query holds name=value pairs separated by &. The fragment (after #) stays in the browser and is never sent to the server.
The program#
# URLs and encodings - taking an address apart, building a query string safely, Base64 and percent-encoding
load "dotnet.ring"
using {
"System"
"System.Net"
"System.Text"
}
func main
# 1. A URL has parts. The Uri class splits them: no searching for ":" and "/" yourself.
oUri = new Uri("https://shop.example.com:8443/products/shoes?color=red&size=42#reviews")
? "1. scheme : " + oUri.Scheme
? " host : " + oUri.Host
? " port : " + oUri.Port
? " path : " + oUri.AbsolutePath
? " query : " + oUri.Query
? " fragment : " + oUri.Fragment
# 2. Default ports: no port in the text gives the port of the scheme
? nl + "2. http port: " + new Uri("http://example.com/").Port + ", https port: " + new Uri("https://example.com/").Port
# 3. Special characters in a query must be encoded: a space, &, = and ? would change the meaning of the address
oWeb = new WebUtility()
cSearch = "rock & roll: 50% off?"
cEncoded = oWeb.UrlEncode(cSearch)
? nl + "3. text : " + cSearch
? " encoded: " + cEncoded
? " decoded back: " + oWeb.UrlDecode(cEncoded)
# 4. Build a URL from a list of values: encode each value, never the separators
aParameters = [["q","rock & roll"],["page",2],["lang","ar"],["note","a b+c"]]
? nl + "4. " + buildUrl("https://example.com/search",aParameters)
# 5. Read a query string: split on & and =, then decode each part
cQuery = "q=rock+%26+roll&page=2&lang=ar"
? nl + "5. the parameters of " + cQuery + ":"
aPairs = parseQuery(cQuery)
for aPair in aPairs
? " " + aPair[1] + " = " + aPair[2]
next
# 6. Combining an address with a relative path
oBase = new Uri("https://example.com/docs/guide/index.html")
oUri = (new Uri).@New([ :baseUri = oBase, :relativeUri = "../images/logo.png" ])
? nl + "6. ../images/logo.png from the guide page: " + oUri.ToString()
# 7. Base64: bytes as safe text (e-mails, JSON, data URLs). It is NOT encryption: anybody can decode it.
oConvert = new Convert()
oUtf8 = new Encoding().UTF8
cBase = oConvert.ToBase64String(oUtf8.GetBytes("Hello, Ring! é"))
? nl + "7. Base64: " + cBase
? " decoded: " + oUtf8.GetString(oConvert.FromBase64String(cBase))
# 8. An address that is not valid
? nl + "8. is 'not a url' valid? " + yesNo(oUri.IsWellFormedUriString("not a url","Absolute"))
? " is 'https://example.com' valid? " + yesNo(oUri.IsWellFormedUriString("https://example.com","Absolute"))
func buildUrl cBase, aParameters
cQuery = ""
for aPair in aParameters
if cQuery != ""
cQuery += "&"
ok
cQuery += aPair[1] + "=" + new WebUtility().UrlEncode("" + aPair[2])
next
return cBase + "?" + cQuery
# "a=1&b=2" -> [["a","1"],["b","2"]], each value decoded
func parseQuery cQuery
aList = []
aParts = str2list(substr(cQuery,"&",nl))
for cPart in aParts
nPos = substr(cPart,"=")
aList + [left(cPart,nPos - 1),new WebUtility().UrlDecode(substr(cPart,nPos + 1))]
next
return aList
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. scheme : https
host : shop.example.com
port : 8443
path : /products/shoes
query : ?color=red&size=42
fragment : #reviews
2. http port: 80, https port: 443
3. text : rock & roll: 50% off?
encoded: rock+%26+roll%3A+50%25+off%3F
decoded back: rock & roll: 50% off?
4. https://example.com/search?q=rock+%26+roll&page=2&lang=ar¬e=a+b%2Bc
5. the parameters of q=rock+%26+roll&page=2&lang=ar:
q = rock & roll
page = 2
lang = ar
6. ../images/logo.png from the guide page: https://example.com/docs/images/logo.png
7. Base64: SGVsbG8sIFJpbmchIMOp
decoded: Hello, Ring! é
8. is 'not a url' valid? no
is 'https://example.com' valid? yesThis program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Uri#
new Uri(text) parses the address and gives you Scheme, Host, Port, AbsolutePath, Query and Fragment. Never cut an address with substr and find: ports, user names, ? inside a fragment and many other details make it go wrong. If no port is written, the port of the scheme is used (80 for http, 443 for https).
Encoding#
Some characters have a meaning in an address: & separates parameters, = joins a name and a value, ? starts the query, % starts an escape. If the text of the user contains them, they must be percent-encoded or they change the meaning: rock & roll would become two parameters. WebUtility.UrlEncode turns each special character into % and two hex digits (& → %26) and a space into +; UrlDecode reverses it.
Building and reading a query#
buildUrl encodes each value and puts = and & between them yourself — the separators must not be encoded. parseQuery does the reverse: first split on &, then on the first =, and decode each value last. If you decoded first, an encoded %26 would turn into a real & and break the split.
Never build addresses or SQL or HTML by adding user text to a string without encoding it for that place. The same rule applies to all three: encode for the place where the text goes.
Relative addresses#
A page at /docs/guide/index.html that links to ../images/logo.png means /docs/images/logo.png. Uri(baseUri, relativeUri) does this resolution for you; because the constructor takes two values it is written with named arguments: dnNew("Uri",[ :baseUri = oBase, :relativeUri = "..." ]).
Base64#
Base64 writes any bytes with 64 safe characters (letters, digits, +, /). It is used in e-mails, JSON and data URLs. It makes the data about a third bigger and it is not encryption — anyone can decode it. For secrets use the tutorial Hashing and encryption.
Checking an address#
IsWellFormedUriString(text, "Absolute") answers yes or no without raising an error. The enum argument is written as text (the tutorial Enums and flags).
What you learned#
Uriand its parts,- encoding and decoding for query strings,
- the order: split first, decode last,
- relative addresses with named constructor arguments,
- Base64.
Exercises#
- Write
getParameter(cUrl, cName)that returns one value of the query of an address. - Build the URL of a search for the text
C# & Ringand check it withUri. - Turn a small text file into a Base64 data URL (
data:text/plain;base64,...).