Web design and hosting, database, cloud and social media solutions that deliver business results
  • Solução de negócio
    • Automação Robótica de Processos
    • Programas
    • Serviços de banco de dados
      • Relatórios
      • Integração de dados
    • Design de Websites
      • Design de logotipo
      • Gateways de pagamento
      • Localização e Tradução Web
      • Otimização de sites
      • Segurança do site
      • Ferramentas Técnicas
    • Serviços Empresariais
      • Amazon Web Services
      • Serviços do Google Cloud
      • Microsoft Azure
    • Microsoft Office
    • Mídia Social
  • Sobre
    • Carreiras
      • Tradutor Inglês-Espanhol
      • Tradutor Inglês-Turco
      • Tradutor Inglês-Japonês
      • Tradutor Inglês-Português
    • Equipe
      • Adrian Anandan
      • Ali Al Amine
      • Ayse Hur
      • Chester Copperpot
      • Gavin Clayton
      • Sai Gangu
      • Suneel Kumar
      • Surya Mukkamala
    • Portfolio
čeština (CS)Deutsch (DE)English (EN-US)English (EN-GB)Español (ES)Français (FR)हिंदी (HI)italiano (IT)日本語 (JA)polski (PL)Português (PT)русский (RU)Türk (TR)中国的 (ZH)

Chamando o Google Tradutor do ASP.NET

Passo a passo: Chamando o Google Translate do ASP.NET usando POST para documentos mais longos do seu código por trás.

If you want to run through this walkthrough, please follow the guide on setting up our test environment.

Experience Level - Intermediate

Introdução

A API do Google Tradutor é boa para realizar traduções bastante complexas e, embora não seja perfeita, pelo menos dará aos seus leitores uma compreensão básica do que você está tentando transmitir.

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.

Ver documentação: veja o código da API do Google Tradutor

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, declaramos uma string de retorno, criamos uma string de URL de solicitação que é rapidamente analisada em uma nova solicitação da web (Req).

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.

Autor

Helpful?

Please note, this commenting system is still in final testing.
Copyright Claytabase Ltd 2020

Registered in England and Wales 08985867

RSSLoginLink Política de CookiesSitemap

Social Media

facebook.com/Claytabaseinstagram.com/claytabase/twitter.com/Claytabaselinkedin.com/company/claytabase-ltd

Get in Touch

+442392064871info@claytabase.comClaytabase Ltd, Unit 3d, Rink Road Industrial Estate, PO33 2LT, United Kingdom
As configurações neste site são definidas para permitir todos os cookies. Estes podem ser alterados em nossa página de configurações e políticas de cookie. Ao continuar a usar este site, você concorda com o uso de cookies.
Ousia Logo
Logout
Ousia CMS Loader