[C#] 使用API调用NLP词法分析
choleraa 发布于2017-12 浏览:8180 回复:9
3
收藏

在开发者Q群里有人反映不会使用API方式调用不了NLP词法分析, 昨晚试了一下, API还是没有坏的^_^ 虚惊一场

因为C#是最好的语言, 所以给大家看一下C#的调用demo.

  • 1. 画一个图形界面

  • 2. 执行步骤

        a. 使用两个Key换一个Token出来

        b. 使用Token和输入的语句, 发个POST请求, 换回结果.

        和大象进入冰箱有异曲同工之妙

 

  • 3. 命名空间及引用
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Script.Serialization;
using System.Windows.Forms;

  这里面使用了一个第三方的Newtonsoft.Json. 这个简直是神作. 可以去这里下载dll, 并且添加引用: https://www.newtonsoft.com/json

此外System.Web.Script这个在我的默认项目里面也没有, 需要手动添加.

 

4. 核心代码

      a. 两个Key换一个Token

     

    public class AccessToken
    {
        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private String clientId = "";
        // 百度云中开通对应服务应用的 Secret Key
        private String clientSecret = "";

        public AccessToken(string appkey, string secretkey)
        {
            this.clientId = appkey;
            this.clientSecret = secretkey;
        }
        // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
        // 返回token示例
        //public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";
        
        public  String getAccessToken()
        {
            //这段照抄应该就可以
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List> paraList = new List>();
            paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
            //两个Key在这里传进去
            paraList.Add(new KeyValuePair("client_id", clientId));
            paraList.Add(new KeyValuePair("client_secret", clientSecret));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            String result = response.Content.ReadAsStringAsync().Result;
            //WARNING: 这个result不是单纯的token, 而是一大堆东西, 需要解析
            return result;
        }
    }

从result中解析出来真正需要的token (我放到了点击Get Token那个按钮的点击事件里面了, 其实放别的地方也可以

        private void button1_Click(object sender, EventArgs e)
        {
            AccessToken accToken = new AccessToken(this.textBoxAppKey.Text, this.textBoxSecretKey.Text);
            string returnedContent = accToken.getAccessToken();
            //this result contains two parts (damned JSON file)
            //we have to split it into two parts and remove unnecessary suffix like brackets
            //Sample of return
            //"{\"access_token\":\"24.39d622b051970e1813476d643f62cadb.2592000.1515943229.282335-10477809\",
            //\"session_key\":\"9mzdCP1R5ugLlNT+jnWkhQDo78Lkn2O8x7j8XcrJ9gJTlfN7nxsY\\/F1WbTykpXZUZs8\\/mh1YRHl1dkQlNpL55fMwiQfebA==\",
            //\"scope\":\"iknow-antispam_spamauth public nlp_simnet nlp_wordemb nlp_comtag nlp_dnnlm_cn brain_nlp_lexer brain_all_scope brain_nlp_comment_tag brain_nlp_dnnlm_cn brain_nlp_word_emb_vec brain_nlp_word_emb_sim brain_nlp_sentiment_classify brain_nlp_simnet brain_nlp_depparser brain_nlp_wordembedding brain_nlp_dnnlm_cn_legacy brain_nlp_simnet_legacy brain_nlp_comment_tag_legacy brain_nlp_lexer_custom wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower bnstest_fasf lpq_\\u5f00\\u653e\",
            //\"refresh_token\":\"25.919a932d9db70b2b491050a8a2a1400b.315360000.1828711229.282335-10477809\",
            //\"session_secret\":\"51b4dabe72d9569f817f8fed4d517d17\",\"expires_in\":2592000}\n"
            Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(returnedContent);
            this.token = obj["access_token"].ToString();
            this.label1.Text = this.token;

        }

     b. 有了token就可以正式调用NLP API了

   public class AccessAPI
   {
        public string GetResultViaAPI(string strToken, string sentence)
        {
            //这里使用Token
            String apiHost = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?access_token=" + strToken;

            Dictionary para = new Dictionary();
            //这里是真正的输入区
            para.Add("text", sentence);
            
            //以下照抄
            Encoding encoding = Encoding.GetEncoding("GBK");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiHost);
            request.Method = "post";
            request.ContentType = "application/json";
            request.KeepAlive = true;
            JavaScriptSerializer json = new JavaScriptSerializer();
            String str = json.Serialize(para);
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GBK"));
            string result = reader.ReadToEnd();
            return result;

        }
    }

 

最后来看一下运行效果:

 

好了, 就到这里~~~

 

 

收藏
点赞
3
个赞
共9条回复 最后由用户已被禁言回复于2022-04
#10卡农LLLL回复于2018-01

产品经理也来共享了.嘿嘿

0
#9荒墨丶迷失回复于2018-01

“无法将数据写入传输连接: 远程主机强迫关闭了一个现有的连接。。”

这个我在java里面见过 是winform程序和服务端  socket抛的异常~

1
#8给我yi把刀回复于2018-01

您好,希望能向您请教个问题。我用C#运行官方示例时运行到下面这句代码时出现了错误:

request.GetRequestStream().Write(buffer, 0, buffer.Length);

System.IO.IOException:“无法将数据写入传输连接: 远程主机强迫关闭了一个现有的连接。。”

这个可能是什么问题导致的啊??

0
#7亓官月彬回复于2017-12

感谢,正为GBK苦恼呢

0
#6choleraa回复于2017-12
#5 荒墨丶迷失回复
原来如此  幸会幸会 哈哈~

回头一起切磋代码~~

0
#5荒墨丶迷失回复于2017-12
#4 choleraa回复
我是ai开放平台的产品经理. 其实不能算开发者, 且算是C#的粉丝吧~~
展开

原来如此  幸会幸会 哈哈~

1
#4choleraa回复于2017-12

我是ai开放平台的产品经理. 其实不能算开发者, 且算是C#的粉丝吧~~

0
#3荒墨丶迷失回复于2017-12

哈哈 go神不在孤单 c#会发扬光大

1
#2goJhou回复于2017-12

很高兴社区除了我还有C#开发者的出现。

欢迎使用C# SDK-CLI,全面接入NLP

2
TOP
切换版块