背景:
我被要求创建一个基本上必须与谷歌翻译 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/