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