asp.net利用google的api做翻译
说明:google提供了一组API可以给我们很方便的实现语言翻译功能,对于我们(中国人)而言,常用的是中文与英文的互译。大家英文好的可以看看GOOGLE的文档:http://code.google.com/apis/ajaxlanguage/documentation/reference.html#LangNameArray
需要使用到JSON.NET在http://www.codeplex.com/Json下载。
什么是序列化?可以看看我前面的文章。http://www.sosuo8.com/article/show.asp?id=2470
其实google已经提供了在JS下很方便的翻译功能,但有些情况下我们却需要在.net下操作。什么情况?采集中文文章并翻译成英文入库,或者是写一个C/S的软件。下面我将主要贴出代码,具体的可以看木子写的文章。
其需要用:
encodeURIComponent
传值。
主要代码:
代码如下:
/// <summary>
/// 替换翻译后的特殊字符,用于换行等
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string TransToHtml(string str)
{
string temp;
temp = str.Replace("003c", "<");
temp = temp.Replace("003e",">");
return temp;
}
/// <summary>
/// 使用WebRequest获取Google翻译后的内容
/// </summary>
/// <param name="str"></param>
/// <param name="strRequestLan"></param>
/// <param name="strResultLan"></param>
/// <returns></returns>
private string GetGoogleTransJSONString(string str, string strRequestLan, string strResultLan)
{
try
{
WebRequest request = HttpWebRequest.Create("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + str + "&langpair=" + strRequestLan + "%7C" + strResultLan);
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
stream.Close();
response.Close();
return responseFromServer;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 翻译
/// </summary>
/// <param name="str">需要翻译的内容</param>
/// <param name="strReuest">原文</param>
/// <param name="strResult">译文</param>
/// <returns></returns>
public string Translate(string str, string strReuestLan, string strResultLan)
{
try
{
if (!string.IsNullOrEmpty(str))
{
TranslateString transtr = (TranslateString)Newtonsoft.Json.JavaScriptConvert.DeserializeObject(GetGoogleTransJSONString(str, strReuestLan, strResultLan),typeof(TranslateString));
if (transtr.responseStatus == 200)
{
return transtr.responseData.translatedText;
}
else
{
return "有错误发生";
}
}
else
{
return str;
}
}
catch (Exception ex)
{
return ex.Message;
}
}
using System;
/// <summary>
///反序列化
/// </summary>
/// {"responseData": {"translatedText":"ahuinan"}, "responseDetails": null, "responseStatus": 200}
[Serializable]
public class TranslateString
{
private TranslatedText _responseData;
private string _responseDetails;
private int _responseStauts;
public TranslatedText responseData
{
get
{
return _responseData;
}
set
{
_responseData = value;
}
}
public string responseDetails
{
get
{
return _responseDetails;
}
set
{
_responseDetails = value;
}
}
public int responseStatus
{
get
{
return _responseStauts;
}
set
{
_responseStauts = value;
}
}
/// <summary>
/// 译文内容
/// </summary>
public class TranslatedText
{
private string _translatedText;
public string translatedText
{
get
{
return _translatedText;
}
set
{
_translatedText = value;
}
}
}
}