有道词典的API使用 C#

20 篇文章 0 订阅
 

今天看接口方面的东西,顺手练习了一把,用有道的API做了一个翻译工具,贴代码吧

 protected void Button1_Click(object sender, EventArgs e)
      

        {
          this.Label1.Text =  YouDaoTranslateTool(this.TextBox1.Text.ToString());
        }

 

 public static string YouDaoTranslateTool(string sourceWord)
        {
            /*
            调用:
http://fanyi.youdao.com/openapi.do?keyfrom=sasfasdfasf&key=1177596287&type=data&doctype=json&version=1.1&q=中国人
            返回的json格式如下:
            {"translation":["The Chinese"],"basic":{"phonetic":"zhōng guó rén","explains":["Chinese","Chinaman","Chinese people","Chinee","chow"]}
             * ,"query":"中国人","errorCode":0,"web":[{"value":["Chinaren","Chinese people","The Chinese","Chinese person"],"key":"中国人"},
             * {"value":["中国人"],"key":"中國人"},{"value":["CHINA LIFE","LFC","china life insurance","YZC"],"key":"中国人寿"},{"value":["Human Rights in China","HRIC"],"key":"中国人权"},
             * {"value":["China Life Insurance Company","China Life Insurance","China Life","China Life Insurance Co Ltd"],"key":"中国人寿保险"},
             * {"value":["Chinese name","Chinese Names in English","Courtesy Name"],"key":"中国人名"},{"value":["Chinese Names"],"key":"中国人的名字"},
             * {"value":["CJOL"],"key":"中国人才热线"},{"value":["American Born Chinese"],"key":"美生中国人"},{"value":["Chinese Characteristics"],"key":"中国人德行"}]}*/
            string serverUrl = @"http://fanyi.youdao.com/openapi.do?keyfrom=sasfasdfasf&key=1177596287&type=data&doctype=json&version=1.1&q="
            + HttpUtility.UrlEncode(sourceWord);
            WebRequest request = WebRequest.Create(serverUrl);
            WebResponse response = request.GetResponse();
            string resJson = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            int textIndex = resJson.IndexOf("translation") + 15;
            int textLen = resJson.IndexOf("\"]", textIndex) - textIndex;
            return resJson.Substring(textIndex, textLen);
        }

其中返回的格式也可以是xml,只需要修改url中德type就行了,具体可以去有道的官网查看,挺好玩的,在用的时候要申请key的,希望有需要的朋友可以用到。
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值