首页 > 代码库 > Sample-Code:Translator
Sample-Code:Translator
<h2>My Spanish Translator</h2> <p> Enter your text in English: </p> <p> <asp:TextBox ID="TextBox1" runat="server" Width="198px"></asp:TextBox> </p> <p> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Translate" /> </p> <p> Here is your translation:</p> <p> <asp:Literal ID="lbl1" runat="server"></asp:Literal> </p>
button code:
string clientID = "<Your ClientID>"; string clientSecret = "<Your Client Secret>"; String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret)); System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails); webRequest.ContentLength = bytes.Length; using (System.IO.Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } System.Net.WebResponse webResponse = webRequest.GetResponse(); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); //Get deserialized object from JSON stream AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); string headerValue = http://www.mamicode.com/"Bearer " + token.access_token; string txtToTranslate = TextBox1.Text; string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"; System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri); translationWebRequest.Headers.Add("Authorization", headerValue); System.Net.WebResponse response = null; response = translationWebRequest.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode); System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument(); xTranslation.LoadXml(translatedStream.ReadToEnd()); lbl1.Text = "Your Translation is: " + xTranslation.InnerText;
AdmAccessToken Class:
public class AdmAccessToken { public string access_token { get; set; } public string token_type { get; set; } public string expires_in { get; set; } public string scope { get; set; } }
Resource from: http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。