using System;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Web;
using System.Globalization;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
namespace TransAPICSharpDemo
{
class Program
{
static async Task Main(string[] args)
{
// 原文
string q = "apple";
// 源语言
string from = "en";
// 目标语言
string to = "zh";
// 改成您的APP ID
string appId = "123123";
Random rd = new Random();
string salt = rd.Next(100000).ToString();
// 改成您的密钥
string secretKey = "123123";
string sign = EncryptString(appId + q + salt + secretKey);
string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
url += "q=" + HttpUtility.UrlEncode(q);
url += "&from=" + from;
url += "&to=" + to;
url += "&appid=" + appId;
url += "&salt=" + salt;
url += "&sign=" + sign;
var resp = await new HttpClient().GetStringAsync(url);
var data = JsonConvert.DeserializeObject<Root>(resp);
foreach (var item in data.trans_result)
{
Console.WriteLine(JsonConvert.SerializeObject(item));
}
Console.ReadLine();
}
//如果好用,请收藏地址,帮忙分享。
public class Trans_resultItem
{
/// <summary>
///
/// </summary>
public string src { get; set; }
/// <summary>
/// 苹果
/// </summary>
public string dst { get; set; }
}
public class Root
{
/// <summary>
///
/// </summary>
public string from { get; set; }
/// <summary>
///
/// </summary>
public string to { get; set; }
/// <summary>
///
/// </summary>
public List<Trans_resultItem> trans_result { get; set; }
}
/// <returns></returns>
public static string UnicodeToString(string srcText)
{
string dst = "";
string src = srcText;
int len = srcText.Length / 6;
for (int i = 0; i <= len - 1; i++)
{
string str = "";
str = src.Substring(0, 6).Substring(2);
src = src.Substring(6);
byte[] bytes = new byte[2];
bytes[1] = byte.Parse(int.Parse(str.Substring(0, 2), NumberStyles.HexNumber).ToString());
bytes[0] = byte.Parse(int.Parse(str.Substring(2, 2), NumberStyles.HexNumber).ToString());
dst += Encoding.Unicode.GetString(bytes);
}
return dst;
}
// 计算MD5值
public static string EncryptString(string str)
{
MD5 md5 = MD5.Create();
// 将字符串转换成字节数组
byte[] byteOld = Encoding.UTF8.GetBytes(str);
// 调用加密方法
byte[] byteNew = md5.ComputeHash(byteOld);
// 将加密结果转换为字符串
StringBuilder sb = new StringBuilder();
foreach (byte b in byteNew)
{
// 将字节转换成16进制表示的字符串,
sb.Append(b.ToString("x2"));
}
// 返回加密的字符串
return sb.ToString();
}
}
}
记录.net 调用百度翻译api
最新推荐文章于 2024-09-06 10:49:39 发布