使用正版的接口,先去微软注册一个Azure账号(需要信用卡),随后配置为免费限量,原则上不花钱.注册扣费1美元,招商银行扣了我10块钱,这是什么鬼汇率....
回归正题,先建立返回翻译结果json对应的类.
namespace EasyNote.Translate.Bing { public class Class1 { public Detectedlanguage detectedLanguage { get; set; } public Translation[] translations { get; set; } public Error error { get; set; } } public class Detectedlanguage { public string language { get; set; } public float score { get; set; } } public class Translation { public string text { get; set; } public Transliteration transliteration { get; set; } public string to { get; set; } } public class Transliteration { public string script { get; set; } public string text { get; set; } } public class Error { public int code { get; set; } public string message { get; set; } } }
然后调用函数,里面的Ocp-Apim-Subscription-Key使用注册后获取的Key,打***的部分替换为自己的.
public static async Task<List<EasyNote.Translate.Bing.Class1>> Bing_Translate(string from, string to, string content) { List<EasyNote.Translate.Bing.Class1> result = null; var url = new Uri($"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={from}&to={to}", UriKind.Absolute); var httpClient = new System.Net.Http.HttpClient(); tContent tc = new tContent { text = content }; List<tContent> tcs = new List<tContent> { tc}; string json = JsonConvert.SerializeObject(tcs); HttpContent httpContent = new StringContent(json); //设置Http的内容标头 httpContent.Headers.ContentType= new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); httpContent.Headers.Add("Ocp-Apim-Subscription-Key", "*********"); var reponse = await httpClient.PostAsync(url, httpContent); string r_json = await reponse.Content.ReadAsStringAsync(); Debug.WriteLine(r_json); try { result = JsonConvert.DeserializeObject<List<EasyNote.Translate.Bing.Class1>>(r_json); } catch (Exception ex) { Debug.Write(ex.Message); } return result; } }
Bing支持的语言比baidu多,相关API文档:
https://docs.microsoft.com/zh-cn/azure/cognitive-services/translator/reference/v3-0-languages