VBScript: URLEncode, URLDecode 함수

ASP에 URL을 인코딩하려면 Server 객체의 URLEncode 메쏘드를 사용하면 된다. 그럼 디코딩은 어떻게 하지? ASP환경이 아닌 환경- 예를 들면 도스창에서 VBScript로 스크립트를 짤 때 – 에서는 Server 객체가 제공이 안되는데 이곳에서는 인코딩이나 디코딩을 어떻게 해야 하는가?

여기에 대한 대안으로 사용할 수 있는 함수인 URLEncode, URLDecode를 소개한다.

Function URLEncode(sStr)  
    Dim i, acode

    URLEncode = sStr

    For i = Len(URLEncode) To 1 Step -1  
        acode = Asc(Mid(URLEncode, i, 1))  
        If (aCode >=48 And aCode <=57) Or (aCode >= 65 And aCode <=90) Or (aCode >= 97 And aCode <=122) Then  
        ' don't touch alphanumeric chars  
        Else  
            Select Case acode  
            Case 32  
                ' replace space with "+"  
                URLEncode = Left(URLEncode, i - 1) & "+" & Mid(URLEncode, i + 1)  
            Case Else  
                ' replace punctuation chars with "%hex"  
                URLEncode = Left(URLEncode, i - 1) & "%" & Hex(acode) & Mid(URLEncode, i + 1)  
            End Select  
        End If  
    Next  
End Function

Function URLDecode(sStr)  
    Dim sTemp, sChar, nLen  
    Dim nPos, sResult, sHex

    On Error Resume Next

    nLen = Len(sStr)

    sTemp = Replace(sStr, "+", " ")  
    For nPos = 1 To nLen  
        sChar = Mid(sTemp, nPos, 1)  
        If sChar = "%" Then  
            If nPos + 2 <= nLen Then  
                sHex = Mid(sTemp, nPos+1, 2)  
                If IsHexaString(sHex) Then  
                    sResult = sResult & Chr(CLng("&H" & sHex))  
                    nPos = nPos + 2  
                Else  
                    sResult = sResult & sChar  
                End If  
            Else  
                sResult = sResult & sChar  
            End If  
            Else  
            sResult = sResult & sChar  
        End If  
    Next

    If Err Then  
        LogError "URLDecode(" & sStr & "). " & Err.description  
    End If

    On Error GoTo 0

    URLDecode = sResult  
End Function

''  
' 문자열이 모두 16진수 문자열로 구성되어 있는지 점검  
' @param sStr 검사할 문자열  
' @return 모두 HEX String으로 이루어져 있으면 true, 아니면 false  
Function IsHexaString( sStr )  
    Dim nPos  
    Dim sChar  
    Dim bReturn

    bReturn = True  
    If sStr <> "" Then  
        For nPos = 1 To Len(sStr)  
            sChar = Mid( sStr, nPos, 1 )  
            If ( sChar < "a" OR sChar > "f" ) And ( sChar < "A" OR sChar > "F") And ( sChar < "0" OR sChar > "9") Then  
                bReturn = False  
            End If  
        Next  
    Else  
        bReturn = False  
    End If

    IsHexaString = bReturn  
End Function