现在的位置: 网页制作教程网站制作经验 >正文
asp语言高级教程

如何将URLEnCode后的字符串解码还原成中文

发表于2016/12/24 网站制作经验 0条评论 ⁄ 热度 3,562℃

我们知道asp的VBScript提供URLEnCode编码函数,它可以将中文做url编码。

比如我们将“网站源码www.webym.net”做url编码:

<%=server.URLEnCode("网站源码下载www.webym.net")%>
输出结果:%E7%BD%91%E7%AB%99%E6%BA%90%E7%A0%81%E4%B8%8B%E8%BD%BDwww%2Ewebym%2Enet

那如果需要解码该如何操作呢?令人遗憾的是asp并没有提供相关的解码函数。

经整理,有两种解码的方法。一种是将以上字符串作为网址url的参数,另外一种是编写解码函数实现。

将编码后的字符串作为utl参数

浏览器可以自动解码还原url编码,那么我们可以将待解码的字符串作为url参数,然后再用request.QueryString来获取。

<a href="demo.asp?s=%E7%BD%91%E7%AB%99%E6%BA%90%E7%A0%81%E4%B8%8B%E8%BD%BDwww%2Ewebym%2Enet">链接</a>

在demo.asp里用request.QueryString("s")就可以取到值。

利用解码函数

<%
Response.Write URLDecode("%E7%BD%91%E7%AB%99%E6%BA%90%E7%A0%81%E4%B8%8B%E8%BD%BDwww%2Ewebym%2Enet")
Public Function URLDecode(ByVal strIn)
URLDecode = ""
Dim sl: sl = 1
Dim tl: tl = 1
Dim key: key = "%"
Dim kl: kl = Len(key)
sl = InStr(sl, strIn, key, 1)
Do While sl>0
If (tl=1 And sl<>1) Or tl<sl Then
URLDecode = URLDecode & Mid(strIn, tl, sl-tl)
End If
Dim hh, hi, hl
Dim a
Select Case UCase(Mid(strIn, sl+kl, 1))
Case "U":'Unicode URLEncode
a = Mid(strIn, sl+kl+1, 4)
URLDecode = URLDecode & ChrW("&H" & a)
sl = sl + 6
Case "E":'UTF-8 URLEncode
hh = Mid(strIn, sl+kl, 2)
a = Int("&H" & hh)'ascii码
If Abs(a)<128 Then
sl = sl + 3
URLDecode = URLDecode & Chr(a)
Else
hi = Mid(strIn, sl+3+kl, 2)
hl = Mid(strIn, sl+6+kl, 2)
a = ("&H" & hh And &H0F) * 2 ^12 Or ("&H" & hi And &H3F) * 2 ^ 6 Or ("&H" & hl And &H3F)
If a<0 Then a = a + 65536
URLDecode = URLDecode & ChrW(a)
sl = sl + 9
End If
Case Else:'Asc URLEncode
hh = Mid(strIn, sl+kl, 2)'高位
a = Int("&H" & hh)'ascii码
If Abs(a)<128 Then
sl = sl + 3
Else
hi = Mid(strIn, sl+3+kl, 2)'低位
a = Int("&H" & hh & hi)'非ascii码
sl = sl + 6
End If
URLDecode = URLDecode & Chr(a)
End Select
tl = sl
sl = InStr(sl, strIn, key, 1)
Loop
URLDecode = URLDecode & Mid(strIn, tl)
End Function
%>
  • 暂无评论