自己动手写谷歌API翻译接口

 
可以看到,利用GET请求方式,带入某些参数,就会返回一个json数组,QueryString参数如下:
 
 
同样的,我们只需要传入这三个参数,就可以获得我们想要的翻译内容,公开方法,代码如下。
 1 static string TranslateGoogleString(string translateContent, string fromLanguage = "zh-CN", string toLanguage = "en")
 2 {
 3   string transRetHtml = string.Empty;
 4  
 5   string encodedStr = HttpUtility.UrlEncode(translateContent); //URL编码
 6   string url = string.Format("http://translate.google.cn/translate_a/single?client=t&sl={0}&tl={1}&hl={0}&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&ssel=6&tsel=3&kc=0&tk=522626|172097&q={2}", fromLanguage, toLanguage, encodedStr);
 7  
 8 try
 9 {
10   var bytes = new WebClient().DownloadData(url);
11   transRetHtml = Encoding.UTF8.GetString(bytes);
12  
13   var index = transRetHtml.IndexOf("]],");
14   transRetHtml = transRetHtml.Substring(0, index + 1).Replace("[[", "");
15   transRetHtml = transRetHtml = transRetHtml.Replace("[\"", "");
16   transRetHtml = transRetHtml.Substring(0, transRetHtml.IndexOf("\""));
17  
18 }
19 catch (Exception ex)
20 {
21 }
22  
23 return transRetHtml;
24 }
我们来试一试:
1 static void Main(string[] args)
2 {
3     string str = TranslateGoogleString("梦想");
4     Console.WriteLine(str);
5     Console.ReadLine();
6 }

 
posted @ 2015-09-02 14:57  虔城墨客  阅读(5790)  评论(1编辑  收藏  举报