首页 /编程语言和算法/VB6/VBA/ASP
 VB6 利用 API 对 URL 进行编码/解码
昨天 17:48

有时您可能需要以编程方式对 URL 进行编码/解码。本文将向您展示使用 2 个未记录的 API 是多么容易。
编码 URL 意味着将任何不寻常的字符转换为转义代码(例如,空格将被 %20 替换)。
解码 URL 意味着将转义代码转换为实际字符(例如,%20 将被空格替换)。    

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

'Converts unsafe characters, such as spaces into their corresponding escape sequences.
'e.g. space => %20
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

'Converts escape sequences back into ordinary characters.
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.abc.com/send 123.asp")

    '//URL Encode Demo
    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

    '//URL Decode Demo
    strURL = InputBox("Enter URL to Decode", "URL Decode Demo", "www.abc.com/send%20123.asp")
    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

运行结果:

www.abc.com/send 123.asp

变成

www.abc.com/send%20123.asp

 
全部回复(0)
首页 | 电脑版 |