Chamando o Google Tradutor do ASP.NET
If you want to run through this walkthrough, please follow the guide on setting up our test environment.
Experience Level - Intermediate
Introdução
Embora o documento seja muito bom para explicar o que acontece quando você usa Java Script, que pode traduzir cerca de 500 caracteres, há muito pouco para quando você precisa traduzir documentos maiores.
Ao usar POST você pode aumentar para 5000 caracteres, por isso desenvolvemos nosso próprio código para enviar uma solicitação de postagem para a API do Google e depois receber a tradução.
Primeiro passo, precisamos adicionar uma classe à nossa pasta App_Code e chamá-la de Translate, lembre-se com o passo a passo para definir a Build Action para Compile.
VB
Imports System.IOImports System.NetImports System.Web.Script.SerializationPublic Class Translate Shared Function GetTranslation(ByVal key As String, ByVal source As String, ByVal target As String, ByVal Text As String) As String ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Dim TranslatedString As String = "" Text = "q=" + Text Dim TranslateRequest As New Uri(String.Format("https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&format=html", key, source, target)) Dim Req As WebRequest = WebRequest.Create(TranslateRequest) Req.Method = "POST" Req.Headers.Add("X-https-Method-Override", "GET") Req.ContentType = "application/x-www-form-urlencoded" Using ReqStr As Stream = Req.GetRequestStream() Dim encoding As New UTF8Encoding() Dim bytes As Byte() = encoding.GetBytes(Text) ReqStr.Write(bytes, 0, bytes.Length) End Using Dim ReturnStr As String Using sr = New StreamReader(Req.GetResponse.GetResponseStream) ReturnStr = sr.ReadToEnd() End Using Dim Reader As New JavaScriptSerializer Dim TranslateJSON As Dictionary(Of String, Object) = Reader.DeserializeObject(ReturnStr) Dim TranslateData As Dictionary(Of String, Object) If TranslateJSON.ContainsKey("data") Then TranslateData = TranslateJSON("data") If TranslateData.ContainsKey("translations") Then For Each pair In TranslateData.Item("translations")(0) TranslatedString = pair.Value.ToString() Next End If End If Return TranslatedString End FunctionEnd Class
Add a page
Within the Pages Section, Add a new page called GoogleTranslate, and then the HTML and code below.
HTML
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title> <script> function UpdateHiddenField(el, id) { nextElSibling(el).value = el.innerHTML; } function nextElSibling(el) { if (el.nextSibling) do { el = el.nextSibling } while (el && el.nodeType !== 1); return el; } </script></head><body> <form id="form1" runat="server"> <div style="max-width:1000px;margin:auto;"> <div style="clear:both;"> <asp:Label ID="KeyLabel" runat="server" AssociatedControlID="LgTo" Text="API Key"></asp:Label> <asp:TextBox ID="KeyValue" runat="server"></asp:TextBox> </div> <div style="float:left;width:50%;background-color:#ddd;"> <div> <asp:Label ID="LgFromLabel" runat="server" AssociatedControlID="LgFrom" Text="From"></asp:Label> <asp:DropDownList runat="server" ID="LgFrom"> <asp:ListItem Text="English" Value="en"></asp:ListItem> <asp:ListItem Text="Français" Value="fr"></asp:ListItem> <asp:ListItem Text="Deutsch" Value="de"></asp:ListItem> </asp:DropDownList> </div> <div style="min-height:400px;border:1px solid #ccc;" contenteditable="true" onkeyup="UpdateHiddenField(this)" id="ContentTextInput" runat="server"></div> <asp:HiddenField ID="ContentText" runat="server"/> </div> <div style="float:left;width:50%;background-color:#ccc;"> <div> <asp:Label ID="LgToLabel" runat="server" AssociatedControlID="LgTo" Text="To"></asp:Label> <asp:DropDownList runat="server" ID="LgTo"> <asp:ListItem Text="English" Value="en"></asp:ListItem> <asp:ListItem Text="Français" Value="fr"></asp:ListItem> <asp:ListItem Text="Deutsch" Value="de" Selected="True"></asp:ListItem> </asp:DropDownList> </div> <div style="min-height:400px;border:1px solid #bbb;" runat="server" id="ContentTrans"></div> </div> <div style="clear:both;text-align:center;"> <asp:Button runat="server" ID="Translation" Text="Translate"/> </div> </div> </form></body></html>
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Protected Sub GetTranslation_Click(sender As Object, e As EventArgs) Handles Translation.Click Dim Key As String = "Your Key" Dim source As String = LgTo.SelectedItem.Text.ToString Dim target As String = LgFrom.SelectedItem.Text.ToString Dim PageText As String = HttpUtility.HtmlDecode(ContentText.InnerHtml) Try ContentTrans.InnerHtml = HttpUtility.HtmlDecode(Translate.GetTranslation(Key, source, target, PageText)) Catch End Try End Sub
O que faz
A função requer quatro entradas, estas são sua chave, idioma de, idioma para e o texto que você deseja traduzir.
Em seguida, definimos o tipo de solicitação, o tipo de conteúdo e, o mais importante, adicionamos um cabeçalho para substituir o método get .
Feito isso, enviamos os dados como um fluxo para o Google (ReqStr).Agora declaramos uma string de retorno (ReturnStr) para manter o JSON retornado do Google e lemos a string de resposta nele.
O próximo passo é criar um JavaScriptSerializer, esta parte foi provavelmente a mais confusa, pois esta era a área mais fraca das minhas habilidades de desenvolvimento na época. O que esta última seção faz é extrair cada seção de texto até chegar à área que queremos e definir nosso texto de retorno como o valor retornado pelo Google. Este pode não ser o código mais elaborado do mundo, então, se você descobrir uma maneira de arrumá-lo, me avise.
O exemplo preenche o conteúdo DIV do outro. Observe a decodificação dupla (do editor e do Google), e tem duas caixas de texto indicando o idioma de e para.