百度翻译API

时间:2024-01-18 22:34:02
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="百度翻译_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><asp:Literal ID="Literal1" runat="server"></asp:Literal> </div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using BDTranslate.Models;
public partial class 百度翻译_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
private TranClass tranClass = new TranClass();
protected void Button1_Click(object sender, EventArgs e)
{
tranClass.From = "zh";
tranClass.To = "en";
WebClient client = new WebClient(); //引用System.Net
string fromTranslate = this.TextBox1.Text; //翻译前的内容
if (!string.IsNullOrEmpty(fromTranslate))
{
// 拼接appid=2015063000000001+q=apple+salt=1435660288+密钥=12345678
//得到字符串1 =2015063000000001apple143566028812345678
long d = DateTimeToUnixTimestamp(DateTime.Now);
string str = "key" + this.TextBox1.Text + d + "密钥"; string md5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + this.TextBox1.Text + "&from=en&to=zh&appid=key&salt="+d+"&sign=" + md5;
var buffer = client.DownloadData(url);
string result = Encoding.UTF8.GetString(buffer);
StringReader sr = new StringReader(result);
JsonTextReader jsonReader = new JsonTextReader(sr); //引用Newtonsoft.Json 自带
JsonSerializer serializer = new JsonSerializer();
var r = serializer.Deserialize<TranClass>(jsonReader); //因为获取后的为json对象 ,实行转换
Literal1.Text = r.Trans_result[].dst; //dst为翻译后的值 }
} /// <summary>
/// 日期转换成unix时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long DateTimeToUnixTimestamp(DateTime dateTime)
{
var start = new DateTime(, , , , , , dateTime.Kind);
return Convert.ToInt64((dateTime - start).TotalSeconds);
} } namespace BDTranslate.Models
{
public class TranClass
{
public string From { get; set; }
public string To { get; set; }
public List<Trans_result> Trans_result { get; set; }
}
public class Trans_result
{
public string src { get; set; }
public string dst { get; set; }
}
}