天天看點

百度翻譯api 調用案例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Web;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.IO;
using Newtonsoft.Json;

namespace ConsoleColorReflection
{
    public class BaiduFanyi
    {
        public static string Appid { get; set; }
        public static string SecretKey { get; set; }
        public static string FromLang { get; set; }
        public static string ToLang { get; set; }
        public static string Query { get; set; }
        public static string SaltWord { get; set; }
        public static string SignWordBeforeMD5 { get; set; }
        public static string SignWordResult { get; set; }
        public static  string UrlString { get; set; }
        public static HttpClient HttpClient { get; set; }
        public static string ResponseMsg { get; set; }
        public static string Result { get; set; }
        public BaiduFanyi()
        {
            Appid = Defualt.Appid;
            SecretKey = Defualt.SecretKey;
            FromLang = Defualt.FromLang;
            ToLang = Defualt.ToLang;
            Query = Defualt.Query;
            Random random = new Random();
            SaltWord = random.Next(32768000, 65536000).ToString();
            UrlString = Defualt.UrlString;


        }
        public  static string  Fanyi(string query)
        {
            BaiduFanyi baiduFanyi = new BaiduFanyi();

            SignWordBeforeMD5 = Appid + query + SaltWord + SecretKey;
            //Console.WriteLine(SignWordBeforeMD5);
            //md5運算
            using (MD5 md5Hash=MD5.Create())
            {
                SignWordResult = GetMd5Hash(md5Hash, SignWordBeforeMD5);
            }
            //Console.WriteLine(UrlString);
            UrlString = string.Format("{0}?q={1}&from={2}&to={3}&appid={4}&salt={5}&sign={6}",UrlString,query,FromLang,ToLang,Appid,SaltWord,SignWordResult);
            Uri uri = new Uri(UrlString);
            using (HttpClient = new HttpClient())
            {
                try
                {
                    WebRequest webRequest = HttpWebRequest.Create(UrlString);
                    WebResponse webResponse = webRequest.GetResponse();
                    using (StreamReader streamReader=new StreamReader(webResponse.GetResponseStream()))
                    {
                        ResponseMsg=Regex.Unescape(streamReader.ReadToEnd());
                    }
                  
                    //Console.WriteLine(ResponseMsg);

                    
                    //Console.WriteLine(ResponseMsg);
                }
                catch (NotImplementedException e)
                {

                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
                Result = string.Empty;
                try
                {
                    var result = JsonConvert.DeserializeObject<dynamic>(ResponseMsg);
                    var results = result.trans_result;
                    foreach (var item in results)
                    {
                        Result += item.dst;
                        //Console.WriteLine(item.dst);
                    }
                }
                catch (Exception ex)
                {

                    Result = string.Format("翻譯錯誤{0}",ex.Message);
                }
               
                
            }
            //Console.WriteLine(Result);
            return Result;
            
        }

        static string GetMd5Hash(MD5 md5Hash, string input)
        {

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
        public class Defualt
        {
            public static string Appid = "Appid";
            public static string SecretKey = "密鑰";
            public static string FromLang = "en";
            public static string To;
            public static string Query = "apple";
            public static string UrlString = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        }
    }
}