简体   繁体   中英

Error on a POST when calling Google Translate API v2 from C#

Background :

I've been requested to create a translation web service which basically must interact with Google Translate apis. Since the text I do need to translate is larger than 2,000 characters I cannot use the GET WebRequest/GET method. Instead, I should use the POST which supports till 5,000 characters.

Tech Notes :

VS 2010 Utlimate, Google Translate API v2 ( http://code.google.com/apis/language/translate/v2/using_rest.html#WorkingResults )

Issue :

I've implemented below code for the POST web request and it works for URLs having a max of 1,489 characters. If the the URL contains 1,490 then an exception is raised: " The remote server returned an error: (414) Request-URI Too Large. "

 using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Net;
        using System.Runtime.Serialization;
        using System.Runtime.Serialization.Json;
        using System.Text;
        using Newtonsoft.Json.Linq;


        string sourceLanguage = "es"; // English
        string targetLanguage = "en"; // Spanish
        string text = "Working from home ( please replace this string for a text longer thant 1,490 characters!!! )"; // Text to be translated

        // url for a web request
        String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
        String url = String.Format(apiUrl, Constants.apiKey, sourceLanguage, targetLanguage, text);

        byte[] bytes = Encoding.ASCII.GetBytes(url);
        Stream outputStream = null;
        string translatedText = string.Empty;

        // web request
        WebRequest webRequest = WebRequest.Create(url);

        // POST method
        webRequest.Method = "POST";
        webRequest.Headers.Add("X-HTTP-Method-Override:GET");
        webRequest.ContentType = "application/x-www-form-urlencoded";

        try
        {
            // send the POST
            webRequest.ContentLength = bytes.Length;
            outputStream = webRequest.GetRequestStream();
            outputStream.Write(bytes, 0, bytes.Length);
        }
        catch (WebException e)
        {
            Console.WriteLine(e.Message, "HttpPost: Request error");
        }

        try
        {

            // get the response
            WebResponse webResponse = webRequest.GetResponse();

            if (webResponse != null)
            {
                // read response stream 
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {

                    JObject obj = JObject.Parse(sr.ReadToEnd());
                    JToken translated = obj.SelectToken("data.translations[0].translatedText");
                    // get translated text into a string
                    translatedText = translated.Value<string>();
                }
            }
        }
        catch (WebException e)
        {
            Console.WriteLine(e.Message, "HttpPost: Response error");
        }

Question :

Does anybody have experience using this translation API and see which is the error here? Can anyone tell me which is the f"$@! error I spent the last 3 hrs looking for!! I'm going crazy with this. Any contribution will be REALLY appreciated. Thanks in advance! :)

Important Note : I was able to overcome the POST issue by following this Post: Google Translate V2 cannot hanlde large text translations from C#

Since you're overriding the GET, you should be able to put the parameters in your request body instead of on the query string. The error you're receiving is perfectly valid if you're passing in a large amount of text. I don't think the RFC specifies a maximum limit, but does provide the 414 error code for the server to be able to respond appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM