百度翻译接口使用c#
2021-03-14 12:27
标签:转换 document vip space selection response style command null https://www.songshizhao.com/blog/blogPage/1004.html 定义baidu返回的json对应的类 调用方法: 百度翻译平台:http://api.fanyi.baidu.com/api/trans/product/apidoc 使用: res.dst是翻译的结果 百度翻译接口使用c# 标签:转换 document vip space selection response style command null 原文地址:https://www.cnblogs.com/Leo_wl/p/12495050.htmlc#使用百度翻译接口(更新修复)
namespace
EasyNote.Translate.Baidu
{
public
class
Rootobject
{
public
string
from {
get
;
set
; }
public
string
to {
get
;
set
; }
public
string
domain {
get
;
set
; }
public
int
type {
get
;
set
; }
public
int
status {
get
;
set
; }
public
int
error {
get
;
set
; }
public
string
msg {
get
;
set
; }
public
Trans_Result[] trans_result {
get
;
set
; }
}
public
class
Trans_Result
{
public
string
src {
get
;
set
; }
public
string
dst {
get
;
set
; }
public
int
prefixWrap {
get
;
set
; }
public
object
[] relation {
get
;
set
; }
public
object
[][] result {
get
;
set
; }
}
}
public
static
async Task
string
from,
string
to,
string
content)
{
// 原文
string
q = content;
// 源语言
// 改成您的APP ID
string
appId =
"这个需要前往百度翻译平台注册获取自己的ID"
;
Random rd =
new
Random();
string
salt = rd.Next(100000).ToString();
// 改成您的密钥
string
secretKey =
"百度翻译平台获取"
;
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;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method =
"GET"
;
request.ContentType =
"text/html;charset=UTF-8"
;
request.UserAgent =
null
;
request.Timeout = 6000;
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using
(WebResponse response = await request.GetResponseAsync())
{
using
(Stream myResponseStream = response.GetResponseStream())
{
using
(StreamReader myStreamReader =
new
StreamReader(myResponseStream, Encoding.GetEncoding(
"utf-8"
)))
{
string
retString = myStreamReader.ReadToEnd();
Debug.WriteLine(retString);
var result = JsonConvert.DeserializeObject
return
result;
}
}
}
}
// 计算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();
}
var res = await Translater.Baidu_Translate(MySettings.Baidu_From, MySettings.Baidu_To,redit.Document.Selection.Text);