例如你在http://mp3.baidu.com/里面搜索“爱你w”你将看到地址栏里面出现
http://mp3.baidu.com/m?f=ms&tn=baidump3&ct=134217728&lf=&rn=&word=%B0%AE%C4%E3w&lm=-1
注意word=后的“%B0%AE%C4%E3w”就是IE对URL编码的结果,也即是GB转换成Unicode
在.net里你怎么获得这样的效果呢?Web.HttpUtility.UrlEncode就是用来搞这个东东的,前提是你先添加对
System.Web.DLL的引用。
这是最简单的方法,如 MsgBox(Web.HttpUtility.UrlEncode("爱你")。(也许你获得的和实际想得到的不一样)
别急 MsgBox(Web.HttpUtility.UrlEncode("爱你", Encoding.Default))。OK没事了吧?谢谢.net带给你的方便吧!
下面是第二种方法,比较麻烦和原始
Dim s As String
Dim s1 As Byte() = System.Text.Encoding.Default.GetBytes("爱你")
Dim i As Integer = 0
While i < s1.Length
s &= "%" & Convert.ToString(s1(i), 16)
i += 1
End While
MsgBox(s)
如果你要在传递的URL里面夹杂英文如“爱你mygirl”就麻烦了,
别激,
看看我定义二个Function就没事了
Function FomartString(ByVal Str As String) As String
Dim strOK As String
Dim i, c As Integer
Dim isChinese As Boolean
For i = 1 To Len(Str)
c = Asc(Mid(Str, i, 1))
If c >= 0 Then 'is not chinese
isChinese = False
strOK &= Mid(Str, i, 1)
Else 'chinese
strOK &= DoConv(Mid(Str, i, 1))
End If
Next
FomartString = strOK
End Function
‘DoConv过程是来个中文转换一个
Function DoConv(ByVal InputString As String) As String
Dim s As String
Dim s1 As Byte() = System.Text.Encoding.Default.GetBytes(InputString)
Dim i As Integer = 0
While i < s1.Length
s &= "%" & Convert.ToString(s1(i), 16)
i += 1
End While
DoConv = s
End Function
现在你要编码什么样的就什么样的了。
调用 msgbox(FomartString("我爱你mygirl"))
没事了吧?