Google Translate V2 cannot transfer large text translations from C #

I implemented C # code using the Google Translation V2 api using the GET method. It successfully translates small texts, but when increasing the length of the text and the duration of 1800 characters (including URI parameters), I get the error "URI is too big."

Well, I burned all the way and investigated the problem on several pages posted on the Internet. They all clearly say that the GET method must be overridden to simulate the POST method (which is designed to support 5000 URIs of characters), but there is no way to find out its sample code.

Does anyone have an 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 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; } 
+6
source share
3 answers

Apparently using WebClient will not work, since you cannot change the headers as needed in the documentation :

Note. You can also use POST to call 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 translation API to process the request as GET (use X-HTTP-Method-Override: GET ).

You can use WebRequest , but you 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); } 
+7
source

The accepted answer seems outdated. Now you can successfully use WebClient (.net 4.5) before POST in the Google translation API to set the X-HTTP-Method-Override header.

Here is some code to show you how to do this.

 using (var webClient = new WebClient()) { webClient.Headers.Add("X-HTTP-Method-Override", "GET"); var data = new NameValueCollection() { { "key", GoogleTranslateApiKey }, { "source", "en" }, { "target", "fr"}, { "q", "<p>Hello World</p>" } }; try { var responseBytes = webClient.UploadValues(GoogleTranslateApiUrl, "POST", data); var json = Encoding.UTF8.GetString(responseBytes); var result = JsonConvert.DeserializeObject<dynamic>(json); var translation = result.data.translations[0].translatedText; } catch (Exception ex) { loggingService.Error(ex.Message); } } 
+1
source

? What kind? It's trivial to send messages using C # - this is right there in the documentation.

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); { // Set type to POST request.Method = "POST"; 

From there, you basically put the data in the fom fields in the content stream.

This does not "mimic the mail method", it completely fulfills the mail request in accordance with the specifications.

Btw. Where is json located here? You say "in C #". No need to use json?

-3
source

Source: https://habr.com/ru/post/909279/


All Articles