注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

午夜阳光

 
 
 

日志

 
 

Asp.NET调用百度翻译 Post方式  

2014-09-01 17:06:38|  分类: C# |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
\
HTML:
 
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="baidu.aspx.cs" Inherits="FanYi_baidu" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>OA翻译</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <asp:TextBox ID="sourceWord" runat="server" Columns="50" Rows="15" style="width:100%;"  
            TextMode="MultiLine"></asp:TextBox>  
        <br />  
        源语言:<asp:DropDownList ID="ddlFrom" runat="server">  
            <asp:ListItem Value="auto">自动检测</asp:ListItem>  
            <asp:ListItem Value="zh">中文</asp:ListItem>  
            <asp:ListItem Value="en">英文</asp:ListItem>  
            <asp:ListItem Value="jp">日文</asp:ListItem>  
        </asp:DropDownList>  
        目标语言:<asp:DropDownList ID="ddlTo" runat="server">  
            <asp:ListItem Value="auto">自动检测</asp:ListItem>  
            <asp:ListItem Value="zh">中文</asp:ListItem>  
            <asp:ListItem Value="en">英文</asp:ListItem>  
            <asp:ListItem Value="jp">日文</asp:ListItem>  
        </asp:DropDownList>  
        <asp:Button ID="Translate"  
            runat="server" Text="翻译" onclick="Translate_Click" />  
        <br />  
        <asp:TextBox ID="resultText" runat="server" TextMode="MultiLine" Rows="15" Columns="50" style="width:100%;"></asp:TextBox>  
    </div>  
    </form>  
</body>  
</html>  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="baidu.aspx.cs" Inherits="FanYi_baidu" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>OA翻译</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="sourceWord" runat="server" Columns="50" Rows="15" style="width:100%;"
            TextMode="MultiLine"></asp:TextBox>
        <br />
        源语言:<asp:DropDownList ID="ddlFrom" runat="server">
            <asp:ListItem Value="auto">自动检测</asp:ListItem>
            <asp:ListItem Value="zh">中文</asp:ListItem>
            <asp:ListItem Value="en">英文</asp:ListItem>
            <asp:ListItem Value="jp">日文</asp:ListItem>
        </asp:DropDownList>
        目标语言:<asp:DropDownList ID="ddlTo" runat="server">
            <asp:ListItem Value="auto">自动检测</asp:ListItem>
            <asp:ListItem Value="zh">中文</asp:ListItem>
            <asp:ListItem Value="en">英文</asp:ListItem>
            <asp:ListItem Value="jp">日文</asp:ListItem>
        </asp:DropDownList>
        <asp:Button ID="Translate"
            runat="server" Text="翻译" onclick="Translate_Click" />
        <br />
        <asp:TextBox ID="resultText" runat="server" TextMode="MultiLine" Rows="15" Columns="50" style="width:100%;"></asp:TextBox>
    </div>
    </form>
</body>
</html>

 

 
C#:
 using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Net;  
using System.Runtime.Serialization;  
using System.Runtime.Serialization.Json;  
using System.Text;  
using System.Web;  
  
public partial class FanYi_baidu : System.Web.UI.Page  
{  
    string url = @"http://openapi.baidu.com/public/2.0/bmt/translate";  
    string requestDetail = "client_id=申请的ID";  
    protected void Page_Load(object sender, EventArgs e)  
    {  
  
    }  
    [DataContract]  
    public class AdmAccessToken  
    {  
        [DataMember]  
        public string from { get; set; }  
        [DataMember]  
        public string to { get; set; }  
        [DataMember]  
        public string error_code { get; set; }  
        [DataMember]  
        public string error_msg { get; set; }  
        [DataMember]  
        public string query { get; set; }  
        [DataMember]  
        public List<TokenResult> trans_result { get; set; }  
    }  
  
    [DataContract]  
    public class TokenResult  
    {  
        [DataMember]  
        public string src { get; set; }  
        [DataMember]  
        public string dst { get; set; }  
    }  
  
    //百度翻译返回数据结构   
    //{   
    //"from": "en",   
    //"to": "zh",   
    //"trans_result": [   
    //    {   
    //        "src": "today",   
    //        "dst": "今天"   
    //    },   
    //    {   
    //        "src": "tomorrow",   
    //        "dst": "明天"   
    //    }   
    //],   
    //"error_code": "52001",   
    //"error_msg": "TIMEOUT",   
    //"query": "he's"   
    //}   
  
    /// <summary>   
    /// 采用Post方式提交数据   
    /// </summary>   
    /// <param name="DatamarketAccessUri">目标网址</param>   
    /// <param name="requestDetails">参数字符串</param>   
    /// <returns></returns>   
    private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)  
    {  
        //Prepare OAuth request    
        WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);  
        webRequest.ContentType = "application/x-www-form-urlencoded";  
        webRequest.Method = "POST";  
        byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);  
        webRequest.ContentLength = bytes.Length;  
        using (Stream outputStream = webRequest.GetRequestStream())  
        {  
            outputStream.Write(bytes, 0, bytes.Length);  
        }  
        using (WebResponse webResponse = webRequest.GetResponse())  
        {  
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));  
            //Get deserialized object from JSON stream   
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());  
            return token;  
        }  
    }  
  
    protected void Translate_Click(object sender, EventArgs e)  
    {  
        resultText.Text = "";  
        if (sourceWord.Text.Trim() != "")  
        {  
            string requestStr = requestDetail + "&from=" + ddlFrom.SelectedValue  
                + "&to=" + ddlTo.SelectedValue  
                + "&q=" + HttpUtility.UrlEncode(sourceWord.Text);  
  
            AdmAccessToken token = HttpPost(url, requestStr);  
            if (token.error_code != null)  
            {  
                resultText.Text = token.error_msg;  
            }  
            else  
            {  
                int n = token.trans_result.Count;  
                for (int i = 0; i < n; i++)  
                {  
                    resultText.Text += token.trans_result[i].dst + (i < n-1 ? "\n" : "");  
                }  
            }  
        }  
        else  
        {  
            resultText.Text = "请输入要翻译的内容";  
        }  
    }  
}  

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;

public partial class FanYi_baidu : System.Web.UI.Page
{
    string url = @"http://openapi.baidu.com/public/2.0/bmt/translate";
    string requestDetail = "client_id=申请的ID";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [DataContract]
    public class AdmAccessToken
    {
        [DataMember]
        public string from { get; set; }
        [DataMember]
        public string to { get; set; }
        [DataMember]
        public string error_code { get; set; }
        [DataMember]
        public string error_msg { get; set; }
        [DataMember]
        public string query { get; set; }
        [DataMember]
        public List<TokenResult> trans_result { get; set; }
    }

    [DataContract]
    public class TokenResult
    {
        [DataMember]
        public string src { get; set; }
        [DataMember]
        public string dst { get; set; }
    }

    //百度翻译返回数据结构
    //{
    //"from": "en",
    //"to": "zh",
    //"trans_result": [
    //    {
    //        "src": "today",
    //        "dst": "今天"
    //    },
    //    {
    //        "src": "tomorrow",
    //        "dst": "明天"
    //    }
    //],
    //"error_code": "52001",
    //"error_msg": "TIMEOUT",
    //"query": "he's"
    //}

    /// <summary>
    /// 采用Post方式提交数据
    /// </summary>
    /// <param name="DatamarketAccessUri">目标网址</param>
    /// <param name="requestDetails">参数字符串</param>
    /// <returns></returns>
    private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
    {
        //Prepare OAuth request 
        WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
        webRequest.ContentLength = bytes.Length;
        using (Stream outputStream = webRequest.GetRequestStream())
        {
            outputStream.Write(bytes, 0, bytes.Length);
        }
        using (WebResponse webResponse = webRequest.GetResponse())
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
            return token;
        }
    }

    protected void Translate_Click(object sender, EventArgs e)
    {
        resultText.Text = "";
        if (sourceWord.Text.Trim() != "")
        {
            string requestStr = requestDetail + "&from=" + ddlFrom.SelectedValue
                + "&to=" + ddlTo.SelectedValue
                + "&q=" + HttpUtility.UrlEncode(sourceWord.Text);

            AdmAccessToken token = HttpPost(url, requestStr);
            if (token.error_code != null)
            {
                resultText.Text = token.error_msg;
            }
            else
            {
                int n = token.trans_result.Count;
                for (int i = 0; i < n; i++)
                {
                    resultText.Text += token.trans_result[i].dst + (i < n-1 ? "\n" : "");
                }
            }
        }
        else
        {
            resultText.Text = "请输入要翻译的内容";
        }
    }
}

 

  评论这张
 
阅读(144)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017