• 调用WebService 实现在线双向翻译


    》先了解一下Web Service的基本概念:

    Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量级的独立的通讯技术。是:通过SOAP在Web上提供的软件服务,使用WSDL文件进行说明,并通过UDDI进行注册。

    XML:(Extensible Markup Language)扩展型可标记语言。面向短期的临时数据处理、面向万维网络,是Soap的基础。

    Soap:(Simple Object Access Protocol)简单对象存取协议。是XML Web Service 的通信协议。当用户通过UDDI找到你的WSDL描述文档后,他通过可以SOAP调用你建立的Web服务中的一个或多个操作。SOAP是XML文档形式的调用方法的规范,它可以支持不同的底层接口,像HTTP(S)或者SMTP。

    WSDL:(Web Services Description Language) WSDL 文件是一个 XML 文档,用于说明一组 SOAP 消息以及如何交换这些消息。大多数情况下由软件自动生成和使用。

    UDDI (Universal Description, Discovery, and Integration) 是一个主要针对Web服务供应商和使用者的新项目。在用户能够调用Web服务之前,必须确定这个服务内包含哪些商务方法,找到被调用的接口定义,还要在服务端来编制软件,UDDI是一种根据描述文档来引导系统查找相应服务的机制。UDDI利用SOAP消息机制(标准的XML/HTTP)来发布,编辑,浏览以及查找注册信息。它采用XML格式来封装各种不同类型的数据,并且发送到注册中心或者由注册中心来返回需要的数据。

    》实现过程:

    1.添加服务引用,翻译的web服务地址:http://fy.webxml.com.cn/webservices/EnglishChinese.asmx

    要注意的事项:在项目右键添加服务引用时,如果不是点高级,添加的服务引用,此时添加引用后,会在Web.Config中生成多余的endpoint节点,应该删除一个节点,不然后启动项目会报错

    image

    2.前台代码:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>WebService实现在线翻译Demo</title>
        <style type="text/css"> 
        *
            {
                margin: 0;
                padding: 0;
                font-family: 'Microsoft YaHei',arial,tahoma,宋体,sans-serif;
                font-size: 14px;
                list-style: none;
            }
            .wrapper {
                background: #FFFFFF;
                border-radius: 10px 10px 10px 10px;
                box-shadow: 0 0 6px #999999;
                margin: 15px auto;
                padding: 10px;
                width: 707px;
                border: 1px solid #C0C0C0;
                overflow:auto;
            }
            body{ background-color: rgb(232,232,232);}
            h1
            {
                text-align: center;
                display: block;
                background-color: #C4DEF7;
                color: #344251;
                font: normal 30px "微软雅黑";
                text-shadow: 1px 1px 0px #DEF3FF;
                padding: 5px 0px;
                margin:10px;
                box-shadow: 0px 2px 6px #000;
                border-radius:10px;
            }
            input[type='button'],input[type='submit'] { padding:1px 5px;}
            #txtInputs{height: 60px;width: 703px;margin-bottom:5px;}
            .head { height:35px; color:#fff; text-align:center; font-size:24px; line-height:1.3em; background-color:#ADC354; border-top:solid 4px #434343; margin-bottom:5px;} 
            #read { display:block; float:right; color:Gray;}
            a.sound { width:30px; height:30px; background:url(../images/play_01.png) no-repeat;display:inline-block;}
            a.sound:hover {background:url(../images/play_02.png) no-repeat; display:inline-block;}
            .result {float:left;}
            </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <h1>WebService实现在线翻译Demo</h1>
            <div class="wrapper">
            <div class="head">中英双向翻译</div>
               <div>
                   <textarea id="txtInputs"></textarea>
                 </div>
                <span id="read">(英文读音)<a class="sound"></a></span> 
               <div class="result"></div>
            </div>
    
        <script src="../js/jquery-1.9.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                //给textarea 注册失去焦点 事件
                $("#txtInputs").blur(function () {
                    var txtInput = $(this).val().trim();
                    var len = txtInput.length;
                    if (len > 0) {
                    //异步获取翻译结果
                        $.post("OnlineTranslation.aspx", { "txtInput": txtInput }, function (data) {
                            $(".result").html("").html(data);
                        });
                    }
                });
                //点击 播放读音
                $(".sound").click(function () {
                    if ($("audio")) {
                        document.getElementById("sound").load();
                        document.getElementById("sound").play();//播放
                    }
                });
    
            })
    
            $.extend({
                //删除左右两端的空格
                trim: function (str) {
                    return str.replace(/(^s*)|(s*$)/g, "");
                }
            });
        </script>
        </form>
    </body>
    </html>

    3.后台代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    
    public partial class _1201WebService_OnlineTranslation : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["txtInput"]))
            {
                string txtInput = Request["txtInput"];//获取用户输入的文本
    
                StringBuilder sb = new StringBuilder();
                if (txtInput.Length > 0)
                {
                    //============web服务返回的数据说明文档=========
                    //DataTable(0) 表名称:Trans,中英文基本翻译,包含一个 Row,5 个 Item
                    // Item(“WordKey”) = 需要进行翻译的单词(输入的单词)
                    // Item(“Pron”) = 音标(英文)、拼音(中文字)
                    // Item(“Info”) = 中文字的国标码、部首、笔画、笔顺信息
                    // Item(“Translation”) = 翻译、解释,多个翻译使用中文“;”分隔
                    // Item(“Mp3”) = 英文单词朗读 Mp3 文件名
                    //(下载 Mp3 地址: http://fy.webxml.com.cn/sound/Mp3 文件名)
                    //如果没有发现单词翻译或出现错误,Item(“Translation”) 会出现以下提示:
                    // WordKey Empty ---- 没有输入单词
                    // Not Found ---- 不能翻译
                    // Error ---- 系统错误
                    // Not Data ---- 没有输据
    
                    //DataTable(1) 表名称:Refer,中译英的相关词条,包含多个 Row,1 个 Item
                    // Item(“Rel”) = 相关词条
    
                    //DataTable(2) 表名称:Sentence,中译英的例句,包含多个 Row,2 个 Item
                    // Item(“Orig”) = 正本
                    // Item(“Trans”) = 译本
    
                    //获取在线双向翻译的Web服务对象
                    ENCN.EnglishChineseSoapClient srvc = new ENCN.EnglishChineseSoapClient();
    
                    //调用Web服务的Translator方法进行翻译
                    DataSet ds = srvc.Translator(txtInput);
                    DataTable transDt = ds.Tables["Trans"];//译文信息
                    DataTable referDt = ds.Tables["Refer"];//相关词条
                    DataTable SentDt = ds.Tables["Sentence"];//例句和翻译
    
                    string wordK = string.Empty;
                    string pron = string.Empty;
                    string trans = string.Empty;
                    string rel = string.Empty;
                    string soundSrc = string.Empty;
    
                    if (transDt.Rows.Count > 0)
                    {
                        pron = transDt.Rows[0]["Pron"].ToString();//音标
                        trans = transDt.Rows[0]["Translation"].ToString();//翻译
                        soundSrc = "http://fy.webxml.com.cn/sound/" + transDt.Rows[0]["Mp3"].ToString();//声音路径
                    }
    
                    if (referDt.Rows.Count > 0)
                    {
                        rel = referDt.Rows[0]["Rel"].ToString();//相关词汇
                    }
    
                    sb.Append("<audio id='sound' src='" + soundSrc + "'></audio>");
                    sb.Append("<p>音标: " + pron + "</p>");
                    sb.Append("<p>翻译: " + trans + "</p>");
                    sb.Append("<p>相关词条: " + rel + "</p><br/>");
    
                    if (SentDt.Rows.Count > 0)
                    {
                        for (int i = 0; i < SentDt.Rows.Count; i++)
                        {
                            sb.Append("<p>例句: " + SentDt.Rows[i]["Orig"].ToString() + "</p>");
                            sb.Append("<p>译文: " + SentDt.Rows[i]["Trans"].ToString() + "</p><br/>");
                        }
                    }
    
                    Response.Write(sb.ToString());
                    Response.End();
                }
                return;
            }
            return;
        }
    
    
          public static string ascEncode(string str)
        {
            if (str == string.Empty)
            {
                return string.Empty;
            }
            else
            {
                System.Text.StringBuilder sb = new StringBuilder();
                char[] chars = str.ToCharArray();
                for (int i = 0; i <= chars.Length - 1; i++)
                {
                    int j = (int)chars[i];
                    if (j > 31 & j < 127)//除ASCII 31-127以外进行编码,以防止网页乱码
                    {
                        sb.Append(chars[i].ToString());
                    }
                    else
                    {
                        sb.Append("&#" + j.ToString() + ";");
                    }
                }
                return sb.ToString();
            }
        }
    }

    4.效果图:

    R{N94Z]3{PXQP_V(RVAB)AO

    开发过程,非常简单,这里不多做说明,音频读取使用了HTML5的<audio>标签,调用了play()方法播放

  • 相关阅读:
    关于hibernate的缓存使用(转)
    Webservice 实践
    三大电商注册登录表单分析
    网上好文搜集
    git简介
    Python程序中的进程操作--—--开启多进程
    进程的创建和结束
    同步异步阻塞和非阻塞
    进程的并行和并发
    进程调度
  • 原文地址:https://www.cnblogs.com/lt-style/p/3452786.html
Copyright © 2020-2023  润新知