谷歌翻译V2不能hanlde从C#大文本翻译 [英] Google Translate V2 cannot hanlde large text translations from C#

查看:279
本文介绍了谷歌翻译V2不能hanlde从C#大文本翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用谷歌翻译API V2使用GET方法实现的C#代码。
它成功地转化小文本,但增加当文本的长度,它需要1800个字符(包括URI参数)我得到了URI太大的错误。



好吧,我烧毁了所有的路径并在发布在互联网上多页调查的问题。他们都清楚地表示,GET方法应该重写来模拟POST方法(这是为了提供5000字符的URI的支持),但没有办法找出一个代码示例它。



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



[修改]下面是代码我中号使用:

 字符串apiUrl ={https://www.googleapis.com/language/translate/v2?key= 0}&放大器;源= {1}&安培;目标= {2}&放大器; q = {3}; 
字符串URL =的String.Format(apiUrl,Constants.apiKey,sourceLanguage,TARGETLANGUAGE,文字);
流的OutputStream = NULL;

字节[]字节= Encoding.ASCII.GetBytes(URL);

//创建HTTP Web请求
的HttpWebRequest的WebRequest =(HttpWebRequest的)WebRequest.Create(URL);
webRequest.KeepAlive = TRUE;
webRequest.Method =POST;
// Overrride的GET作为记录在谷歌的实况方法。
webRequest.Headers.Add(X-HTTP-方法-覆盖:GET);
webRequest.ContentType =应用/的X WWW的形式,进行了urlencoded

//发送POST

{
webRequest.ContentLength = bytes.Length;
的OutputStream = webRequest.GetRequestStream();
outputStream.Write(字节,0,bytes.Length);
outputStream.Close();
}
赶上(HttpException E)
{
/*...*/
}


$ { b $ b //得到响应
HttpWebResponse WebResponse类=(HttpWebResponse)webRequest.GetResponse();
如果(webResponse.StatusCode == HttpStatusCode.OK&放大器;&安培;!WebRequest的= NULL)
{
//使用(StreamReader的SR =新的StreamReader读取响应流
(WebResponse类.GetResponseStream(),Encoding.UTF8))
{
串LISTA = sr.ReadToEnd();

DataContractJsonSerializer序列化=新DataContractJsonSerializer(typeof运算(TranslationRootObject));
MemoryStream的流=新的MemoryStream(Encoding.UTF8.GetBytes(LISTA));
TranslationRootObject tRootObject =(TranslationRootObject)serializer.ReadObject(流);
串previousTranslation =的String.Empty;

//反序列化
的for(int i = 0; I< tRootObject.Data.Detections.Count;我++)
{
串translatedText = tRootObject.Data .Detections [I] .TranslatedText.ToString();
如果(我== 0)
{
文本= translatedText;
}
,否则
{
如果
{
文本=文字++ translatedText(text.Contains(translatedText)!);
}
}
}
返回文本;
}
}
}
赶上(HttpException E)
{
/*...*/
}

返回文本;
}


解决方案

显然使用 Web客户端将无法工作,因为你不能改变头根据需要的 nofollow的>:




请注意:您还可以使用POST来如果你想在一个请求发送更多的数据调用API。在POST身体的参数必须小于5K字。要使用POST,你必须使用 X-HTTP-方法,覆盖头告诉翻译API来当作一个GET请求(使用 X -HTTP - 方法 - 覆盖:GET )




您可以使用的WebRequest ,但你需要添加 X-HTTP-方法,覆盖标题:

  VAR请求= WebRequest.Create(URI); 
request.Method =POST;
request.ContentType =应用/的X WWW的形式,进行了urlencoded
request.Headers.Add(X-HTTP-方法 - 替换,GET);

变种体=新的StringBuilder();
body.Append(键= ​​SECRET);
body.AppendFormat(与&源= {0},HttpUtility.UrlEncode(源));
body.AppendFormat(与&目标= {0},HttpUtility.UrlEncode(目标));
// -
body.AppendFormat(与& Q = {0},HttpUtility.UrlEncode(文本));

VAR字节= Encoding.ASCII.GetBytes(body.ToString());
如果(bytes.Length> 5120)抛出新ArgumentOutOfRangeException(文字);

request.ContentLength = bytes.Length;
使用(VAR输出= request.GetRequestStream())
{
output.Write(字节,0,bytes.Length);
}


I've implemented C# code using the Google Translation V2 api with the GET Method. It successfully translates small texts but when increasing the text length and it takes 1,800 characters long ( including URI parameters ) I'm getting the "URI too large" error.

Ok, I burned down all the paths and investigated the issue across multiple pages posted on Internet. All of them clearly says the GET method should be overriden to simulate a POST method ( which is meant to provide support to 5,000 character URIs ) but there is no way to find out a code example to of it.

Does anyone has any example or can provide some information?

[EDIT] Here is the code I'm using:

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

解决方案

Apparently using WebClient won't work as you cannot alter the headers as needed, 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).

You can use WebRequest, but you'll need to add the 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);
}

这篇关于谷歌翻译V2不能hanlde从C#大文本翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆