C#使用百度翻译API

API网址:

http://developer.baidu.com/wiki/index.php?title=帮助文档首页/百度翻译/翻译API


核心代码:

   /// <summary>
    /// 请求百度接口
    /// </summary>
    /// <param name="sub">要翻译的文本</param>
    /// <param name="from">from语言</param>
    /// <param name="to">翻译为语言</param>
    /// <returns></returns>
    static private string CallInterface(string sub, string from, string to)
    {

        HttpContext.Current.Application.Lock();
        if (HttpContext.Current.Application["baidu"] == null)
        {
            HttpContext.Current.Application["baidu"] = 1;
        }
        else
        {
            HttpContext.Current.Application["baidu"] = (int)HttpContext.Current.Application["baidu"] + 1;
        }
        HttpContext.Current.Application.UnLock();
        string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id={0}&q={1}&from={2}&to={3}", CLIENT_ID, sub, from, to);
        string down = "", result = "";
        try
        {
            WebClient wc = new WebClient();
            down = wc.DownloadString(url);
        }
        catch (Exception)
        {

        }
        JsonData jd = JsonMapper.ToObject(down);
        if (JsonDataContainsKey(jd, "error_code"))
        {
            result += sub;
        }
        else
        {
            JsonData jdResult = jd["trans_result"];
            for (int j = 0; j < jdResult.Count; j++)
            {
                JsonData jdDst = jdResult[j]["dst"];
                result += jdDst.ToString();
            }
        }
        return result;
    }

    static public bool JsonDataContainsKey(JsonData data, string key)
    {
        bool result = false;
        if (data == null)
            return result;
        if (!data.IsObject)
        {
            return result;
        }
        IDictionary tdictionary = data as IDictionary;
        if (tdictionary == null)
            return result;
        if (tdictionary.Contains(key))
        {
            result = true;
        }
        return result;
    }

支持的翻译方向:

from字段 to字段 翻译方向
auto auto 自动识别
zh en 中 -> 英
zh jp 中 -> 日

语种编码

目前支持13种语言,如下所示:

语种 代码 语种 代码
中文 zh 英语 en
日语 jp 韩语 kor
西班牙语 spa 法语 fra
泰语 th 阿拉伯语 ara
俄罗斯语 ru 葡萄牙语 pt
粤语 yue 文言文 wyw
白话文 zh 自动检测 auto
德语 de 意大利语 it

JsonData使用了LitJSON库。

你可能感兴趣的:(百度,编码,C#,英语,语言)