82 lines
3.3 KiB
C#
82 lines
3.3 KiB
C#
using Thousandto.Core.Base;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Text;
|
|
using JSONNode = UnityEngine.Gonbest.MagicCube.JSONNode;
|
|
|
|
namespace Thousandto.Code.Logic
|
|
{
|
|
public class Translator
|
|
{
|
|
static string host = "https://api.cognitive.microsofttranslator.com";
|
|
static string path = "/translate?api-version=3.0";
|
|
|
|
// NOTE: Replace this example key with a valid subscription key.
|
|
static string key = "06e4adadda08414fb5031f0c56d83849";
|
|
static Dictionary<string, string> dic = new Dictionary<string, string>()
|
|
{
|
|
{LanguageConstDefine.CH, "zh-Hans" },
|
|
{LanguageConstDefine.TW, "zh-Hant" },
|
|
{LanguageConstDefine.TH, "th" },
|
|
{LanguageConstDefine.KR, "ko" },
|
|
{LanguageConstDefine.EN, "en" },
|
|
{LanguageConstDefine.JP, "ja" },
|
|
{LanguageConstDefine.VIE, "vi" }
|
|
};
|
|
|
|
public static string Translate(string text = "Hello Dinghuaqiang", string lang = LanguageConstDefine.CH)
|
|
{
|
|
string params_ = "";
|
|
if (dic.ContainsKey(lang))
|
|
params_ = string.Format("&to={0}", dic[lang]);
|
|
else
|
|
params_ = "&to=zh-Hans";
|
|
string uri = host + path + params_;
|
|
string str = string.Format("[{{\"Text\":\"{0}\"}}]", text);
|
|
byte[] data = Encoding.UTF8.GetBytes(str);
|
|
|
|
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
|
|
request.Method = "POST";
|
|
ServicePointManager.ServerCertificateValidationCallback =
|
|
new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
|
|
request.ContentType = "application/json; charset=UTF-8";
|
|
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
|
|
|
|
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
|
|
Stream newStream = request.GetRequestStream();
|
|
|
|
// Send the data.
|
|
newStream.Write(data, 0, data.Length);
|
|
newStream.Close();
|
|
|
|
// Get response
|
|
HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
|
|
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
|
|
string content = reader.ReadToEnd();
|
|
JSONNode json = JSONNode.Parse(content);
|
|
JSONNode noticeData = json[0];
|
|
JSONNode transData = noticeData["translations"];
|
|
|
|
string lanStr = "";
|
|
var itor = transData.Childs.GetEnumerator();
|
|
while (itor.MoveNext())
|
|
{
|
|
var child = itor.Current["text"];
|
|
if (child == null || child.Value == null)
|
|
continue;
|
|
lanStr = child.Value;
|
|
}
|
|
return lanStr;
|
|
}
|
|
public static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
|
|
System.Security.Cryptography.X509Certificates.X509Chain chain,
|
|
System.Net.Security.SslPolicyErrors errors)
|
|
{
|
|
// Always accept
|
|
return true; //总是接受
|
|
}
|
|
}
|
|
}
|