您的位置:首页 > 编程语言 > ASP

asp.net Google的translate工具翻译 API

2008-12-10 00:00 761 查看
在这篇,我就利用C#写一个小程序,翻译:
思路是这样的:
1:发送POST(或者GET)
2:获取POST(或者GET)的响应
3:正则匹配我们想要的值。
发生POST(或者GET)的函数:
public static string GetGetRequest(string urlP,string encode){ 
if(null==urlP) return null; 
string StrRetP = null; 
Stream dataStream = null; 
try{ 
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(urlP); 
myHttpWebRequest.Timeout = 10000; // 10 secs 
HttpWebResponse Objresponse =(HttpWebResponse)myHttpWebRequest.GetResponse(); 
//Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page 
if(Objresponse.StatusDescription == "OK"){//HttpStatusCode.OK 
dataStream = Objresponse.GetResponseStream (); 
Encoding objE = String.IsNullOrEmpty(encode)?Encoding.GetEncoding(0):Encoding.GetEncoding(encode); 
StreamReader r = new StreamReader(dataStream,objE); 
StrRetP= r.ReadToEnd(); 
} 
}catch(Exception e){ 
StrRetP =e.Message; 
}finally{ 
if(null!=dataStream) dataStream.Close(); 
} 
return StrRetP; 
}

这个我在前面的一些文章中有所介绍。
然后正则匹配的函数:
public static string GetMatchString(string text,string pattern,int point){ 
if(String.IsNullOrEmpty(text)||String.IsNullOrEmpty(pattern))return String.Empty; 
Regex rx = new Regex(pattern,RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); 
Match match = rx.Match(text); 
string word=""; 
if (match.Success) word = match.Groups[point].Value; 
return word.Trim(); 
}

这个数根据一个正则表达数,返回匹配的值。
直接进入Main主体:
public static void Main(string[] args){ 
string mess ="我们"; 
Console.WriteLine(HttpUtility.UrlEncode("我们")); 
mess = GetGetRequest("http://translate.google.com/translate_t?langpair="+HttpUtility.UrlEncode("zh-CN|en")+ "&text="+HttpUtility.UrlEncode(mess,System.Text.UnicodeEncoding.GetEncoding( "Gb2312")),"utf-8"); 
//Console.WriteLine(mess); 
mess = GetMatchString(mess,@"(<div id=result_box dir=""ltr"">)([?:\s\S]*?)(</div>)",2); 
Console.WriteLine(mess); 
}

注意的是
HttpUtility.UrlEncode(mess,System.Text.UnicodeEncoding.GetEncoding( "Gb2312"))
这句,无法识别UrlEncode的字符编码,这里需要指明。
OK,然后csc了,编译一下,下载一下吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: