强大的微软Microsoft Translator翻译接口

一、前言

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

二、实现流程

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

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

强大的微软Microsoft Translator翻译接口_第1张图片

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

强大的微软Microsoft Translator翻译接口_第2张图片

 

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

强大的微软Microsoft Translator翻译接口_第3张图片

 

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, 0, 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翻译接口_第4张图片

 

 

你可能感兴趣的:(强大的微软Microsoft Translator翻译接口)