小编典典

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

json

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

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

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

[ 编辑 ]这是我正在使用的代码:

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;
    }

阅读 304

收藏
2020-07-27

共1个答案

小编典典

根据文档WebClient,显然无法使用标题,因为您无法根据需要更改标题:

注意:如果要在单个请求中发送更多数据,也可以使用POST调用API。qPOST正文中的参数必须少于5K个字符。要使用POST,您必须使用X-HTTP- Method-Override标头来告诉Translate API将请求视为GET(使用X-HTTP-Method-Override: GET)。

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

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);
}
2020-07-27