Sometimes you might need to Encode/Decode URL programatically. This article will show you how easy it is using 2 undocumented APIs.
Encoding URL means convert any unusual character into escape code (e.g. space will be replaced by %20).
Decoding URL means convert escape code into actaul character (e.g. %20 will be replaced by space).
Step-By-Step Example
- Create a standard exe project - Add the following code in form1 |
Click here to copy the following block | Private Const MAX_PATH As Long = 260 Private Const ERROR_SUCCESS As Long = 0
Private Const URL_ESCAPE_SEGMENT_ONLY As Long = &H2000 Private Const URL_ESCAPE_PERCENT As Long = &H1000 Private Const URL_UNESCAPE_INPLACE As Long = &H100000
Private Const URL_INTERNAL_PATH As Long = &H800000 Private Const URL_DONT_ESCAPE_EXTRA_INFO As Long = &H2000000 Private Const URL_ESCAPE_SPACES_ONLY As Long = &H4000000 Private Const URL_DONT_SIMPLIFY As Long = &H8000000
Private Declare Function UrlEscape Lib "shlwapi" Alias "UrlEscapeA" _ (ByVal pszURL As String, _ ByVal pszEscaped As String, _ pcchEscaped As Long, _ ByVal dwFlags As Long) As Long
Private Declare Function UrlUnescape Lib "shlwapi" Alias "UrlUnescapeA" _ (ByVal pszURL As String, _ ByVal pszUnescaped As String, _ pcchUnescaped As Long, _ ByVal dwFlags As Long) As Long
Private Sub Form_Load() Dim strURL As String, strEncodedURL As String, strDecodedURL As String, ret As Long
strURL = InputBox("Enter URL to Encode", "URL Encode Demo", "www.binaryworld.net/send feedback.aspx")
strEncodedURL = Space$(MAX_PATH) ret = UrlEscape(strURL, strEncodedURL, MAX_PATH, URL_DONT_SIMPLIFY) If ret = 0 Then strEncodedURL = Left$(strEncodedURL, MAX_PATH) MsgBox "Encoded URL : " & vbCrLf & strEncodedURL End If
strURL = InputBox("Enter URL to Decode", "URL Decode Demo", "www.binaryworld.net/send%20feedback.aspx") strDecodedURL = Space$(MAX_PATH) ret = UrlUnescape(strURL, strDecodedURL, MAX_PATH, URL_DONT_SIMPLIFY) If ret = 0 Then strDecodedURL = Left$(strDecodedURL, MAX_PATH) MsgBox "Decoded URL : " & vbCrLf & strDecodedURL End If End Sub |
- Press F5 to run the project |
|