c# - Google Translate V2 无法处理来自 C# 的大文本翻译

标签 c# json post google-translate

我已经使用 Google Translation V2 api 和 GET 方法实现了 C# 代码。 它成功翻译了小文本,但是当增加文本长度并且需要 1,800 个字符长(包括 URI 参数)时,我收到“URI 太大”错误。

好的,我烧毁了所有路径并在 Internet 上发布的多个页面上调查了这个问题。他们都明确表示应该重写 GET 方法以模拟 POST 方法(这意味着为 5,000 个字符的 URI 提供支持)但是没有办法找到它的代码示例。

有没有人有任何例子或可以提供一些信息?

[EDIT] 这是我使用的代码:

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);
            Stream outputStream = null;

        byte[] bytes = Encoding.ASCII.GetBytes(url);

        // create the http web request
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.KeepAlive = true;
        webRequest.Method = "POST";
        // Overrride the GET method as documented on Google's docu.
        webRequest.Headers.Add("X-HTTP-Method-Override: GET");
        webRequest.ContentType = "application/x-www-form-urlencoded";

        // send POST
        try
        {
            webRequest.ContentLength = bytes.Length;
            outputStream = webRequest.GetRequestStream();
            outputStream.Write(bytes, 0, bytes.Length);
            outputStream.Close();
        }
        catch (HttpException e)
        {
            /*...*/
        }

        try
        {
            // get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            if (webResponse.StatusCode == HttpStatusCode.OK && webRequest != null)
            {
                // read response stream 
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    string lista = sr.ReadToEnd();

                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationRootObject));
                    MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(lista));
                    TranslationRootObject tRootObject = (TranslationRootObject)serializer.ReadObject(stream);
                    string previousTranslation = string.Empty;

                    //deserialize
                    for (int i = 0; i < tRootObject.Data.Detections.Count; i++)
                    {
                        string translatedText = tRootObject.Data.Detections[i].TranslatedText.ToString();
                        if (i == 0)
                        {
                            text = translatedText;
                        }
                        else
                        {
                            if (!text.Contains(translatedText))
                            {
                                text = text + " " + translatedText;
                            }
                        }
                    }
                    return text;
                }
            }
        }
        catch (HttpException e)
        {
            /*...*/
        }

        return text;
    }

最佳答案

显然使用 WebClient 将不起作用,因为您无法根据需要更改 header ,per the documentation :

Note: You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).

您可以使用 WebRequest,但您需要添加 X-HTTP-Method-Override header :

var request = WebRequest.Create (uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-HTTP-Method-Override", "GET");

var body = new StringBuilder();
body.Append("key=SECRET");
body.AppendFormat("&source={0}", HttpUtility.UrlEncode(source));
body.AppendFormat("&target={0}", HttpUtility.UrlEncode(target));
 //--
body.AppendFormat("&q={0}", HttpUtility.UrlEncode(text));

var bytes = Encoding.ASCII.GetBytes(body.ToString());
if (bytes.Length > 5120) throw new ArgumentOutOfRangeException("text");

request.ContentLength = bytes.Length;
using (var output = request.GetRequestStream())
{
    output.Write(bytes, 0, bytes.Length);
}

关于c# - Google Translate V2 无法处理来自 C# 的大文本翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9432422/

相关文章:

c# - 我们可以以编程方式比较具有相同分辨率的不同图像吗?

c# - RDLC 报告中的渲染 PDF 中不显示 Base64 图像

json - 如何在 7.02 之前的 ABAP 中编码 JSON

objective-c - 在 RestKit for iOS 中执行 postObject 时忽略响应

python - 真的可以用 python 发布文件吗?

post - Golang 重置服务发布方法发布数据未定义

c# - ASP.NET MVC 与 Winforms MVC

c# - 编译后更改应用程序名称、图标和程序集信息

.net - 使用 JSON 传递 .NET System.DateTime 以便客户端 javascript 可以构造 javascript Date 对象的最佳方法是什么?

javascript - 无法从我的网络服务器读取本地服务器上的 json 文件