有道词典的API使用 C#

 

今天看接口方面的东西,顺手练习了一把,用有道的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的,希望有需要的朋友可以用到。

你可能感兴趣的:(myself,.net)