VBScript: URLEncode, URLDecode 함수

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

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

  1. Function URLEncode(sStr)
  2. Dim i, acode
  3.  
  4. URLEncode = sStr
  5.  
  6. For i = Len(URLEncode) To 1 Step -1
  7. acode = Asc(Mid(URLEncode, i, 1))
  8. If (aCode >=48 And aCode <=57) Or (aCode >= 65 And aCode <=90) Or (aCode >= 97 And aCode <=122) Then
  9. ' don't touch alphanumeric chars
  10. Else
  11. Select Case acode
  12. Case 32
  13. ' replace space with "+"
  14. URLEncode = Left(URLEncode, i - 1) & "+" & Mid(URLEncode, i + 1)
  15. Case Else
  16. ' replace punctuation chars with "%hex"
  17. URLEncode = Left(URLEncode, i - 1) & "%" & Hex(acode) & Mid(URLEncode, i + 1)
  18. End Select
  19. End If
  20. Next
  21. End Function
  22.  
  23. Function URLDecode(sStr)
  24. Dim sTemp, sChar, nLen
  25. Dim nPos, sResult, sHex
  26.  
  27. On Error Resume Next
  28.  
  29. nLen = Len(sStr)
  30.  
  31. sTemp = Replace(sStr, "+", " ")
  32. For nPos = 1 To nLen
  33. sChar = Mid(sTemp, nPos, 1)
  34. If sChar = "%" Then
  35. If nPos + 2 <= nLen Then
  36. sHex = Mid(sTemp, nPos+1, 2)
  37. If IsHexaString(sHex) Then
  38. sResult = sResult & Chr(CLng("&H" & sHex))
  39. nPos = nPos + 2
  40. Else
  41. sResult = sResult & sChar
  42. End If
  43. Else
  44. sResult = sResult & sChar
  45. End If
  46. Else
  47. sResult = sResult & sChar
  48. End If
  49. Next
  50.  
  51. If Err Then
  52. LogError "URLDecode(" & sStr & "). " & Err.description
  53. End If
  54.  
  55. On Error GoTo 0
  56.  
  57. URLDecode = sResult
  58. End Function
  59.  
  60. ''
  61. ' 문자열이 모두 16진수 문자열로 구성되어 있는지 점검
  62. ' @param sStr 검사할 문자열
  63. ' @return 모두 HEX String으로 이루어져 있으면 true, 아니면 false
  64. Function IsHexaString( sStr )
  65. Dim nPos
  66. Dim sChar
  67. Dim bReturn
  68.  
  69. bReturn = True
  70. If sStr <> "" Then
  71. For nPos = 1 To Len(sStr)
  72. sChar = Mid( sStr, nPos, 1 )
  73. If ( sChar < "a" OR sChar > "f" ) And ( sChar < "A" OR sChar > "F") And ( sChar < "0" OR sChar > "9") Then
  74. bReturn = False
  75. End If
  76. Next
  77. Else
  78. bReturn = False
  79. End If
  80.  
  81. IsHexaString = bReturn
  82. End Function

One thought on “VBScript: URLEncode, URLDecode 함수”

Leave a Reply

Your email address will not be published. Required fields are marked *