public static async Task <TranslateResponse> TranslateText(string input, lang langInput = lang.auto, lang langOutput = lang.zh_CN) { var res = new TranslateResponse(); try { var client = new HttpClient(); const string sl = "auto"; var tl = langOutput.ToString().Replace("_", "-"); var hl = langInput.ToString().Replace("_", "-"); var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={sl}&tl={tl}&hl={hl}&dt=t&dt=bd&dj=1&source=input&tk=501776.501776&q={input}"; var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var text = await response.Content.ReadAsStringAsync(); var translateResult = JsonConvert.DeserializeObject <TranslateResult>(text); res.IsSuccess = true; res.Result = translateResult; res.Response = text; } } catch (Exception ex) { Debug.WriteLine("GoogleTranslateLib.Translate [error] = " + ex); res.IsSuccess = false; res.Exception = ex; res.MessageError = ex.Message; } return(res); }
public static async Task <TranslateResult> TranslateText(string input, lang lang_in = lang.en, lang lang_out = lang.vi, string TemplateRequest = "https://translate.google.com/translate_a/single?client=webapp&sl={lang_in}&tl={lang_out}&hl=vi&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&pc=1&otf=1&ssel=3&tsel=3&kc=1&tk={tk}&q={input}") { var r = new TranslateResult { IsSuccess = false, lang_in = lang_in, lang_out = lang_out, Text_in = input, Text_out = input, ResponseCode = null }; try { string tk = computed_tk(input); string url = TemplateRequest .Replace("{lang_in}", lang_in.ToString()) .Replace("{lang_out}", lang_out.ToString()) .Replace("{tk}", tk.ToString()) .Replace("{input}", Uri.EscapeUriString(input)); Debug.WriteLine(url); var client = new RestClient(url); var request = new RestRequest(Method.GET); foreach (var item in cookies) { request.AddCookie(item.Name, item.Value); } var restResponse = await client.ExecuteTaskAsync(request); r.ResponseCode = restResponse.StatusCode; r.ResponseText = restResponse.Content; if (r.ResponseCode == HttpStatusCode.OK) { r.IsSuccess = true; r.Text_out = Regex.Match(r.ResponseText, "\\[\\[\\[\"([^\"]+)").Groups[1].Value; } else { Count_fail++; } } catch (Exception ex) { Debug.WriteLine(input + ": " + ex); } return(r); }