// build our query and send it to the translate API private String Translate_String(String text, String target) { String requestUrl = "https://www.googleapis.com/language/translate/v2?key=" + _APIKey + "&source=" + _SelectedLangCode + "&target=" + target + "&q="; requestUrl += HttpUtility.UrlEncode(text); //Console.Write(requestUrl); TranslateAPIResponse resp = Make_HTTPRequest(requestUrl); if (resp != null) { if (resp.DataSets.TranslatedText.Length == 0) { return(null); } return(resp.DataSets.TranslatedText[0].Text); } return(null); }
// make a request to the translate api private TranslateAPIResponse Make_HTTPRequest(string requestUrl) { try { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format("Could not connect to Google API (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } _ValidConfiguration = true; DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(TranslateAPIResponse)); object objResponse = jsonSerializer.ReadObject(response.GetResponseStream()); TranslateAPIResponse jsonResponse = objResponse as TranslateAPIResponse; return(jsonResponse); } } catch (Exception e) { MessageBox.Show(e.Message + " - Check your API key."); _ValidConfiguration = false; return(null); } }
// Query the translate api for the list of languages available reported in language targetLang private void Request_AvailableLanguages(String targetLang) { String requestUrl = "https://www.googleapis.com/language/translate/v2/languages?key=" + _APIKey + "&target=" + targetLang; TranslateAPIResponse resp = Make_HTTPRequest(requestUrl); // clear out the check-boxes used to select the languages to translate into if (_DestinationCheckbox != null) { for (int i = 0; i < _DestinationCheckbox.Length; i++) { this.Controls.Remove(_DestinationCheckbox[i]); } } // if we got a valid response populate the combo-boxes and check-boxes with the available languages in the target language if (resp != null) { _DestinationCheckbox = new CheckBox[resp.DataSets.Languages.Length]; _SupportedLanguages = resp.DataSets.Languages; Populate_SourceLanguages(targetLang); Create_DestinationLangCheckBoxes(); } }