简体   繁体   English

从C#调用Google Translate API v2时在POST上出错

[英]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. 我被要求创建一个翻译网络服务,该服务基本上必须与Google Translate API进行交互。 Since the text I do need to translate is larger than 2,000 characters I cannot use the GET WebRequest/GET method. 由于我确实需要翻译的文本大于2,000个字符,因此我无法使用GET WebRequest / GET方法。 Instead, I should use the POST which supports till 5,000 characters. 相反,我应该使用支持多达5,000个字符的POST。

Tech Notes : 技术说明

VS 2010 Utlimate, Google Translate API v2 ( http://code.google.com/apis/language/translate/v2/using_rest.html#WorkingResults ) 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. 我已经为POST Web请求实现了以下代码,它适用于最大1489个字符的URL。 If the the URL contains 1,490 then an exception is raised: " The remote server returned an error: (414) Request-URI Too Large. " 如果URL包含1,490,则引发异常:“ 远程服务器返回错误:(414)请求URI太大。

 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? 是否有人有使用此翻译API的经验,然后看这里是哪个错误? 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! :) 谁能告诉我这是我过去3个小时内一直在寻找的f“ $ @!错误!!我为此而发疯。任何贡献都将不胜感激。在此先感谢!:)

Important Note : I was able to overcome the POST issue by following this Post: Google Translate V2 cannot hanlde large text translations from C# 重要说明 :通过遵循以下博文,我能够解决POST问题: Google Translate V2无法处理来自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. 由于您要覆盖GET,因此应该可以将参数放在请求正文中,而不是查询字符串中。 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. 我认为RFC没有指定最大限制,但确实为服务器提供了414错误代码,以便能够正确响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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