c# - 从 C# 调用 Google Translate API v2 时 POST 出错

标签 c# json post httpwebrequest google-translate

背景:

我被要求创建一个基本上必须与谷歌翻译 api 交互的翻译网络服务。由于我确实需要翻译的文本超过 2,000 个字符,因此我无法使用 GET WebRequest/GET 方法。相反,我应该使用最多支持 5,000 个字符的 POST。

技术说明:

VS 2010 Utlimate,谷歌翻译 API v2 (http://code.google.com/apis/language/translate/v2/using_rest.html#WorkingResults)

问题:

我已经为 POST 网络请求实现了以下代码,它适用于最多 1,489 个字符的 URL。如果 URL 包含 1,490,则会引发异常:“远程服务器返回错误:(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");
        }

问题:

有没有人有使用这个翻译 API 的经验,看看这里的错误是什么?任何人都可以告诉我这是 f"$@! 我花了最后 3 个小时寻找的错误!!我对此感到疯狂。任何贡献将不胜感激。提前致谢!:)

重要说明: 通过关注这篇文章,我能够克服 POST 问题:Google Translate V2 cannot hanlde large text translations from C#

最佳答案

由于您要覆盖 GET,您应该能够将参数放在请求正文中而不是查询字符串中。如果您传递大量文本,您收到的错误是完全有效的。我不认为 RFC 指定了最大限制,但确实为服务器提供了 414 错误代码以便能够适本地响应。

关于c# - 从 C# 调用 Google Translate API v2 时 POST 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317226/

相关文章:

javascript - 从 JSON 数据中获取以 Node.JS 中的前缀开头的每个键

c++ - 在 DLL 中使用的最简单的 C++ PUSH 通知/POST 解决方案?

c# - 登录 ASP.NET Core 3.1 后如何获取用户信息

c# - C# 中的轻量级类到 MySQL 记录映射?

ios - 如何处理循环中的json错误或停止它

javascript - 从文本文件值创建 JSON 对象

javascript - 在非 jQuery 函数中使用 jQuery post 时出现问题

html - 使用 HTTP POST 获取 HTML 表单提交上的 JSON 数据

c# - 无法识别的数据库格式

c# - 在 C# 中,为什么将 key 固定在内存中更安全?