一、前言

当我们需要对日文、韩文等语言转换中文字符的时候,就用到了微软提供的翻译接口。

二、实现流程

1.首先注册一个账号 https://datamarket.azure.com/account

2.账户信息填写,注意国家/地区一定不要选择简体中文,以免后面找不到免费的功能,有些国家会有功能限制。

3.然后点击左侧的开发人员,注册一个应用程序

4.然后搜索Microsoft Translator,并点击进去,可以选择套餐,免费的话每个月只能转换两百万个字符,缴费就能选择更高级别套餐

5.现在我注册免费的,注册成功后,在我的账户-》我的数据里面可以看到

三、代码实现

        private void button3_Click(object sender, EventArgs e)
        {
            string errorCode;
            richTextBox1.Text = Biyabi.Common.MicrosoftTranslator.TranslateString(textBox1.Text, "ja", "zh-CHS", out errorCode);
            textBox2.Text = errorCode;

        }
   public static class MicrosoftTranslator
    {
        /// <summary>
        /// http方式
        /// </summary>
        /// <param name="text"></param>
        /// <param name="fromCulture"></param>
        /// <param name="toCulture"></param>
        /// <param name="errorCode"></param>
        /// <returns></returns>
        public static string TranslateString(string text, string fromCulture, string toCulture, out string errorCode)
        {
            string translateResult = "";
            errorCode = "";

            AdmAccessToken admToken;

            //使用应用程序名,密码
            //AdmAuthentication admAuth = new AdmAuthentication("TranslateHelper", "******");
            //使用账户名,密码
            AdmAuthentication admAuth = new AdmAuthentication("应用程序客户端ID", "应用程序客户端密钥");

            try
            {
                admToken = admAuth.GetAccessToken();

                //string text = "查询条件";
                //string from = "zh-CHS";
                //string to = "en";

                string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text="
                    + System.Web.HttpUtility.UrlEncode(text)
                    + "&from=" + fromCulture
                    + "&to=" + toCulture;

                string authToken = "Bearer" + " " + admToken.access_token;

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Headers.Add("Authorization", authToken);

                WebResponse response = null;
                try
                {
                    response = httpWebRequest.GetResponse();
                    using (Stream stream = response.GetResponseStream())
                    {
                        System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));

                        translateResult = (string)dcs.ReadObject(stream);
                    }
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.Message);
                    errorCode = e.Message;
                }
            }
            catch (WebException e)
            {
                //ProcessWebException(e);
                errorCode = e.Message;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                errorCode = ex.Message;
            }

            return translateResult;
        }

        //http://api.microsofttranslator.com/V2/Soap.svc 添加这个服务引用引用
        /// <summary>
        /// soap方式
        /// </summary>
        /// <param name="text"></param>
        /// <param name="fromCulture"></param>
        /// <param name="toCulture"></param>
        /// <param name="errorCode"></param>
        /// <returns></returns>
        public static string TranslateStringBySoap(string text, string fromCulture, string toCulture, out string errorCode)
        {
            string translateResult = "";
            errorCode = "";

            AdmAccessToken admToken;

            //使用应用程序名,密码
            //AdmAuthentication admAuth = new AdmAuthentication("TranslateHelper", "******");
            //使用账户名,密码
            AdmAuthentication admAuth = new AdmAuthentication("应用程序客户端ID", "应用程序客户端密钥");

            try
            {
                admToken = admAuth.GetAccessToken();

                string authToken = "Bearer" + " " + admToken.access_token;

                MicrosoftTranslatorService.LanguageServiceClient client = new MicrosoftTranslatorService.LanguageServiceClient();
                translateResult = client.Translate(authToken, text, fromCulture, toCulture, "text/html", "", "general");

            }
            catch (WebException e)
            {
                errorCode = e.Message;
            }
            catch (Exception ex)
            {
                errorCode = ex.Message;
            }

            return translateResult;
        }

        private static void ProcessWebException(WebException e)
        {
            //MessageBox.Show(e.ToString());
            // Obtain detailed error information
            string strResponse = string.Empty;
            using (HttpWebResponse response = (HttpWebResponse)e.Response)
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
                    {
                        strResponse = sr.ReadToEnd();
                    }
                }
            }
            //MessageBox.Show(string.Format("Http status code={0}, error message={1}", e.Status, strResponse));
        }
    }

    [DataContract]
    public class AdmAccessToken
    {
        [DataMember]
        public string access_token { get; set; }
        [DataMember]
        public string token_type { get; set; }
        [DataMember]
        public string expires_in { get; set; }
        [DataMember]
        public string scope { get; set; }
    }

    public class AdmAuthentication
    {
        public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
        private string clientId;
        private string cientSecret;
        private string request;

        public AdmAuthentication(string clientId, string clientSecret)
        {
            this.clientId = clientId;
            this.cientSecret = clientSecret;
            //If clientid or client secret has special characters, encode before sending request
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));
        }

        public AdmAccessToken GetAccessToken()
        {
            return HttpPost(DatamarketAccessUri, this.request);
        }

        private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
        {
            //Prepare OAuth request
            WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
            webRequest.ContentLength = bytes.Length;
            using (Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, , bytes.Length);
            }
            using (WebResponse webResponse = webRequest.GetResponse())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
                //Get deserialized object from JSON stream
                AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                return token;
            }
        }
    }

结果展示:

强大的微软Microsoft Translator翻译接口的更多相关文章

  1. 华为Mate 10牵手Microsoft Translator,让离线翻译可媲美在线神经网

    ​编者按:日前,华为新发布的Mate 10手机系列采用Microsoft Translator技术实现了AI驱动型离线翻译功能.华为Mate 10是首款具有NPU(专用神经处理单元)的手机,可用于加速 ...

  2. Microsoft Translator发布粤语文本翻译

    今天,Microsoft Translator发布了粤语的文本翻译,新的语言增加将继续丰富微软翻译产品的生态系统*,让更多组织和个人能够快速且高效地实现翻译应用.在中国,大有约5500万人使用粤语(语 ...

  3. 在Application中集成Microsoft Translator服务之翻译语言代码

    Microsoft  Translator支持多种语言,当我们获取服务时使用这些代码来表示我们是使用哪种语言翻译成什么语言,以下是相关语言对应的代码和中文名 为了方便我已经将数据库上传到云盘上,读者可 ...

  4. 微软 Microsoft

    微软(Microsoft Corporation) (NASDAQ:MSFT,港交所:4338),是一家基于美国的跨国电脑科技公司,是世界PC(Personal Computer,个人计算机)机软件开 ...

  5. 在Application中集成Microsoft Translator服务之使用http获取服务

    一.创建项目 首先我们来创建一个ASP.NET Application 选择时尚时尚最时尚的MVC,为了使演示的Demo更简单,这里选择无身份验证 二.创建相关类 项目需要引入之前两个类AdmAcce ...

  6. 在Application中集成Microsoft Translator服务之获取访问令牌

    我在这里画了一张图来展示业务逻辑 在我们调用microsoft translator server之前需要获得令牌,而且这个令牌的有效期为10分钟.下表列出所需的参数和对于的说明 参数 描述 clie ...

  7. Microsoft Translator:打破语言障碍 拓展全球沟通新机遇

    作者:Olivier Fontana, 微软研究院Microsoft Translator产品战略总监 世界越来越小,全球协作.共同创新已经成为常态.在微软研究院,我们对此尤为感同身受——从北京到雷德 ...

  8. Microsoft Translator:打破语言障碍 拓展全球沟通新机遇

    Translator:打破语言障碍 拓展全球沟通新机遇"> 作者:Olivier Fontana, 微软研究院Microsoft Translator产品战略总监 世界越来越小,全球协 ...

  9. Microsoft Translator:消除面对面交流的语言障碍

    ​ Translator:消除面对面交流的语言障碍" title="Microsoft Translator:消除面对面交流的语言障碍"> ​ James Simm ...

随机推荐

  1. php把数组保存成文件格式

    php把数组保存为文件格式的函数实例,或许有的还没听说过可以把数组保存成文件,其实这样做也是另有它用的,两种方法各有千秋,有兴趣的PHP爱好者敬请参阅: $file="./cache/fil ...

  2. 视图必须派生自 WebViewPage 或 WebViewPage错误解决方法

    1,在每个视图上面添加 @inherits System.Web.Mvc.WebViewPage 2,将views中的web.config COPY到新的视图模版文件夹下,就可以了

  3. java获取当前时间

    /////////////////获取时间方法一////////////////////////////// java.util.Date uDate=new java.util.Date(); Sy ...

  4. 判断iOS设备是否越狱

    - (BOOL)isJailbroken { BOOL jailbroken = NO; NSString *cydiaPath = @"/Applications/Cydia.app&qu ...

  5. 转:VC中UpdateData()函数的使用

    VC中UpdateData()函数的使用 UpdateData(FALSE)与UpdateData(TRUE)是相反的过程     UpdateData(FALSE)是把程序中改变的值更新到控件中去  ...

  6. log4net 学习笔记

    记入最基本的用法 : refer : http://www.cnblogs.com/aehyok/archive/2013/05/07/3066010.html <configuration&g ...

  7. C语言#pragma预处理

    在所有的预处理指令中,#pragma 指令可能是最复杂的了,它的作用是设定编译器的状态或者是指示编译器完成一些特定的动作.#pragma 指令对每个编译器给出了一个方法,在保持与C 和C ++语言完全 ...

  8. 一个简单的以User权限启动外部应用程序

    BOOL ExecuteAsUser(LPCWSTR lpszUserName, LPCWSTR lpszPassword, LPCWSTR lpszApplication, LPCWSTR lpsz ...

  9. 有关autoresizingMask属性遇到的一个小问题

    前言:在讲述这个小问题之前,我们有必要先了解一下UIViewAutoresizing的有关属性概念和使用详解. 参考:自动布局之autoresizingMask使用详解(Storyboard& ...

  10. js点击按钮,放大对应图片代码

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...