After writing the previous article in PHP using Google's translate API, I suddenly wanted to make an ASP class so that asp users could use it. Then I started writing and found that I had forgotten a lot about asp. For example, the theme, the idea is exactly the same as the C# article, I just converted it into the ASP implementation method. Look directly at the code:
Copy the code code as follows:
Class GoogleTranslator
subClass_Initialize()
RURI=http://translate.google.com/translate_t?langpair={0}&text={1}
End Sub
Private Opt_ '
Property Get Opt
Opt=Opt_
End Property
Property Let Opt(Opt_s)
Opt_=Opt_s
End Property
Private RURI
Function AnalyzeChild(patrn,texts,IPos)
Dim regEx, Match, Matches
Set regEx = New RegExp
regEx.IgnoreCase = true
regEx.Global = True
regEx.Pattern = patrn
regEx.Multiline = True
DimRetStr
Set Matches = regEx.Execute(texts)
If(Matches.Count > 0)Then RetStr= Matches(0).SubMatches(IPos)
AnalyzeChild=RetStr
Set regEx =Nothing
End Function
Function getHTTPPage(url)
dim objXML
set objXML=server.createobject(MSXML2.XMLHTTP)' definition
objXML.open GET,url,false'open
objXML.send()'send
If objXML.readystate<>4 then
exit function
End If
getHTTPPage=BytesToBstr(objXML.responseBody)
set objXML=nothing'close
if err.number<>0 then err.Clear
End Function
Function BytesToBstr(body)
dim objstream
set objstream = Server.CreateObject(adodb.stream)
objstream.Type = 1
objstream.Mode =3
objstream.Open
objstream.Write body
objstream.Position = 0
objstream.Type = 2
objstream.Charset = utf-8
'Convert the original default UTF-8 encoding to GB2312 encoding, otherwise directly using XMLHTTP to call a web page with Chinese characters will result in garbled code
BytesToBstr = objstream.ReadText
objstream.Close
set objstream = nothing
End Function
Public Function GetText(str)
If(isempty(str)) Then Exit Function
Dim newUrl,Rs
newUrl=Replace(Replace(RURI,{0},Server.URLEncode(Opt)),{1},Server.URLEncode(str))
Rs=getHTTPPage(newUrl)
GetText = AnalyzeChild((<div id=result_box dir=ltr>)([?:/s/S]*?)(</div>),Rs,1)
End Function
Sub class_Terminate
End Sub
End Class
Then when using:
Copy the code code as follows:
DimObj
Set Obj = new GoogleTranslator
Obj.Opt=zh-CN|en
response.write(Obj.GetText(us))
Then that's it. It should be noted that because any of Google's products are in UTF-8 format, this asp file is saved in UTF-8 format and added at the beginning:
<%@ LANGUAGE=VBScript CodePage=65001%>
<%Option Explicit
'... Copy my code above
That's it.