Skip to content

RealBasic: URL Encoding/Decoding

I was working on a RealBasic project last night and found myself needing a URL encode/decode routine. RealBasic does not have one and I was not able to find any sample online, so I decided to look for a quick and dirty Visual Basic routine and convert it to RealBasic. It’s not the most elegant solution but it met my needs. The original VB code by Igor can be found here.

URL Encoding Converted to RealBasic:
[sourcecode language=”vb”]
Function URLEncode(s as String) As String
Dim TempAns As String
Dim CurChr As Integer
CurChr = 1
Do Until CurChr – 1 = Len(s)
Select Case Asc(Mid(s, CurChr, 1))
Case 48 To 57, 65 To 90, 97 To 122
TempAns = TempAns + Mid(s, CurChr, 1)
Case 32
TempAns = TempAns + "%" + Hex(32)
Case Else
TempAns = TempAns +"%" + Right("0" + Hex(Asc(Mid(s, CurChr, 1))), 2)
End Select

CurChr = CurChr + 1
Loop

return TempAns

End Function
[/sourcecode]

URL Decoding Converted to RealBasic:
[sourcecode language=”vb”]
Function URLDecode(s as String) As String
Dim TempAns As String
Dim CurChr As Integer

CurChr = 1

Do Until CurChr – 1 = Len(s)
Select Case Mid(s, CurChr, 1)
Case "+"
TempAns = TempAns + " "
Case "%"
TempAns = TempAns + Chr(Val("&h" + Mid(s, CurChr + 1, 2)))
CurChr = CurChr + 2
Case Else
TempAns = TempAns + Mid(s, CurChr, 1)
End Select

CurChr = CurChr + 1
Loop

return TempAns
End Function
[/sourcecode]

One change to note from the original is that I made the encoding routine always convert “+” to its hex equivalent.

Tags:

5 thoughts on “RealBasic: URL Encoding/Decoding”

  1. Thanks for the nice code-snippet. But it is not working with special characters like ü. It gives %FC as a result, but to make RBs ShowURL work, you will need UTF8 ecoding which gives %C3%BC as a result. But I haven’s figured out how to accomplish this.

    1. OK I figured it out! Here is what you need to do:

      in the beginning tell RB to use UTF8:
      s = s.DefineEncoding(Encodings.UTF8)

      Then replace ALL calls to
      Len with LenB
      Mid with MidB
      Right with RightB
      Asc with AscB

      that did the trick for me and made ShowURL work properly.

Leave a Reply

Your email address will not be published.