1 Function RemoveHTML()Function RemoveHTML(strHtml)
2 if strHtml<>"" then
3 dim s_str as string
4 s_str=regex.replace(strHtml,"<[^>]+>","")
5 s_str=replace(s_str," ","")
6 return s_str
7 end if
8 End Function
9
10 Function china_to_english()Function china_to_english(texts,languages)
11 Dim payload As String = "hl=zh-CN&IE=UTF8&text="& texts &"&langpair="& languages &""
12 dim str_return as string
13 Dim req As WebRequest = WebRequest.Create("http://translate.google.com/translate_t") ' 開始取連接.
14 req.Credentials = CredentialCache.DefaultCredentials '取得默認
15 req.Method = "POST" '以POST方式發送,這裡默認是以GET方式發送
16 req.ContentType = "application/x-www-form-urlencoded" 'POST方式需在傳送這個編碼,如果上傳文件,則修為multipart/form-data
17 req.timeout=10000 '連接超時定時
18 req.ContentLength = payload.Length '頭部長度
19 Dim encoding As Encoding = Encoding.GetEncoding("UTF-8") '轉換成流,大部網站一般轉換成UTF-8就可以了,注意是大寫的編碼
20 Dim bytes As Byte() = Encoding.GetBytes(payload) '轉換成流
21 req.ContentLength = bytes.Length '傳送流的長度
22 Dim newStream As Stream = req.GetRequestStream() '轉換寫入
23 newStream.Write(bytes, 0, bytes.Length) '寫入傳送流
24 newStream.Close() '關閉
25 '上面發送完成,下面取得服務器返回
26 Dim res As HttpWebResponse = CType(req.GetResponse(), HttpWebResponse) ' 傳遞返回標識
27 if res.StatusDescription="ok" then ' 返回取得狀態.
28 current.response.write("暫時無法連接到網站,請換用另一個程序")
29 current.response.end()
30 end if
31 Dim dataStream As Stream = res.GetResponseStream() ' 返回給指針
32 Dim reader As New StreamReader(dataStream,encoding.getencoding("gb2312")) ' 讀
33 Dim responseFromServer As String = reader.ReadToEnd() ' 讀取所有
34
35 str_return=responseFromServer '賦值回傳
36
37 reader.Close() '接下來三個關閉
38 dataStream.Close()
39 res.Close()
40
41 dim ss as string = str_return
42 ss = regex.replace(ss,"(?i:(.+)(\<div)(.+)(\>)(.+)(\<\/div\>)(.+))","$5") '提取我們所要的譯文
43 ss = RemoveHTML(ss) '刪除Html
44 ss = ss.substring(3) '刪除翻譯二字
45 return ss '函數返回
46 End function
47
48 在調用china_to_english(texts,languages)需要傳兩個參數第一個為要譯的文字,第二個是要進行相對譯的語種代碼.
例:中譯英,其第二個參數為:zh-Cn|en
我導入的命名空間如下:
Imports System
Imports System.Web
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Web.HttpContext
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Net