
C#实现百度智能云文档翻译
namespace BaiduTranslateLibrary
{
public static class TranslateFunction
{
public static void TestTranslate()
{
TranslateConfig translateConfig = new TranslateConfig() {
appId = "xxxxx",
passWord = "xxxx"
};
string filepath = @"C:\Users\cn49ak\Downloads\xxxx.pdf";
var verificationservice = translateConfig.TranslateVerificationService(filepath, "en", "zh");
var translateservice = translateConfig.Translate(verificationservice.fileId, filepath, "en", "zh");
}
/// <summary>
/// 校验服务
/// </summary>
/// <returns></returns>
public static PostVerificationResult TranslateVerificationService(this TranslateConfig translateConfig,string filepath, string languageFrom, string languageTo)
{
string appId = translateConfig.appId,
passWord = translateConfig.passWord,
randomNum = translateConfig.GetRandomNumber;
long timestamp = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
string safeFileName = Path.GetFileName(filepath);
// NPOIFileContext.FileRead(filepath);
string extension = Path.GetExtension(filepath).Substring(1).ToLower();
string UrlRequest = "https://fanyi-api.baidu.com/api/trans/vip/doctrans?";
string ortherparams = "appid=" + appId + "&from=" + languageFrom + "&to=" + languageTo + "×tamp=" + timestamp + "&type=" + extension +"&";
//+ "&sign=" + md5Sign;
string md5Sign = MD5EX.GetMD5HashFromFile(filepath).ToLower();
// 拼接
string md5Sign2 = MD5EX.EncryptString(ortherparams + md5Sign + passWord).ToLower();
string FullRequest = UrlRequest + ortherparams + "sign=" + md5Sign2;
string m_postResult = PostFile(FullRequest, filepath);
PostVerificationResult m_postResultds = new JavaScriptSerializer().Deserialize<PostVerificationResult>(m_postResult);
return m_postResultds;
}
public static string PostFile(string url, string fileName)
{
//验证文件是否存在
if (File.Exists(fileName) == false)
throw new Exception("发送文件不存在!");
FileInfo file = new FileInfo(fileName);
string boundary = "qianle";//分隔符
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
//构造请求体
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] byteEnd = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //结束标识 --xxxx--
StringBuilder strContent = new StringBuilder();
strContent
.Append("Content-Disposition:form-data;name=\"file\";filename=\"" + file.Name + "\"")
.AppendLine()
.Append("Content-Type:application/octet-stream")
.AppendLine()
.AppendLine(); //特别说明,Content-Disposition 前边不能添加换行符号
byte[] byteContent = Encoding.UTF8.GetBytes(strContent.ToString());
byte[] byteFile = File.ReadAllBytes(fileName);
//执行发送
req.Method = "POST";
req.ContentType = $"multipart/form-data;charset=utf-8;boundary={boundary}";
//req.UserAgent = UserAgent;
req.ContinueTimeout = 20000;
var reqStrem = req.GetRequestStream();
reqStrem.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); //文件开始
reqStrem.Write(byteContent, 0, byteContent.Length);//文件信息
reqStrem.Write(byteFile, 0, byteFile.Length);//文件内容
reqStrem.Write(byteEnd, 0, byteEnd.Length); //文件结束
reqStrem.Close();
WebResponse resp = req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
resp.Close();
return result;
}
public static PostResult Translate(this TranslateConfig translateConfig, string field,string filepath, string languageFrom, string languageTo,string outPutType = "docx")
{
string appId = translateConfig.appId,
passWord = translateConfig.passWord,
randomNum = translateConfig.GetRandomNumber;
long timestamp = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
string extension = Path.GetExtension(filepath).Substring(1).ToLower();
string md5Sign = MD5EX.EncryptString(appId + randomNum + passWord).ToLower();
string FullRequest = "https://fanyi-api.baidu.com/api/trans/vip/doctrans?type=" + extension + "&outPutType=" + outPutType + "&fileId=" + field + "×tamp=" + timestamp + "&from=" + languageFrom + "&to=" + languageTo + "&appid=" + appId + "&sign=" + md5Sign;
string m_Content = new WebClient().DownloadString(FullRequest);
PostResult m_postResult = new JavaScriptSerializer().Deserialize<PostResult>(m_Content);
return m_postResult;
}
public class TranslateConfig
{
public TranslateConfig()
{
randomNum = new Random().Next().ToString();
}
public string appId { get; set; }
public string passWord { get; set; }
private string randomNum { get; set; }
public string GetRandomNumber => randomNum;
}
public class PostVerificationResult
{
public string Error_code { set; get; }
public string Error_msg { set; get; }
public string From { set; get; }
public string To { set; get; }
public object data { get; set; }
public int charCount { get; set; }
public string fileId { get; set; }
/// <summary>
/// 预算:单位分
/// </summary>
public int amount { set; get; }
}
public class PostResult
{
public string Error_code { set; get; }
public string Error_msg { set; get; }
public string From { set; get; }
public string To { set; get; }
public TranslateContent[] Trans_result { set; get; }
}
public class TranslateContent
{
public string Src { set; get; }
public string Dst { set; get; }
}
}
}
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
评价
排名
2
文章
657
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 :
好是好,这个对效率影响大不大哇,效率高不高
一个bug让程序员走上法庭 索赔金额达400亿日元
剑轩 : 有点可怕
ASP.NET Core 服务注册生命周期
剑轩 :
http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术