java使用百度UNIT
因为网上不太有java的教学所以写一下以便以后用到或帮助大家一起理解
第一步是注册机器人,官网:https://ai.baidu.com/unit/home。注册和测试技能官网都有,就不多做介绍。
工具类:
1.AuthService
package com.ssx.robot.baidu; import org.springframework.boot.configurationprocessor.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; /** * 获取token类 */ public class AuthService { /** * 获取权限token * @return 返回示例: * { * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567", * "expires_in": 2592000 * } */ public static String getAuth() { // 官网获取的 API Key 更新为你注册的 String clientId = ""; // 官网获取的 Secret Key 更新为你注册的 String clientSecret = ""; return getAuth(clientId, clientSecret); } /** * 获取API访问token * 该token有一定的有效期,需要自行管理,当失效时需重新获取. * @param ak - 百度云官网获取的 API Key * @param sk - 百度云官网获取的 Securet Key * @return assess_token 示例: * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567" */ public static String getAuth(String ak, String sk) { // 获取token地址 String authHost = "https://aip.baidubce.com/oauth/2.0/token?"; String getAccessTokenUrl = authHost // 1. grant_type为固定参数 + "grant_type=client_credentials" // 2. 官网获取的 API Key + "&client_id=" + ak // 3. 官网获取的 Secret Key + "&client_secret=" + sk; try { URL realUrl = new URL(getAccessTokenUrl); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.err.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) != null) { result += line; } /** * 返回结果示例 */ System.err.println("result:" + result); JSONObject jsonObject = new JSONObject(result); String access_token = jsonObject.getString("access_token"); return access_token; } catch (Exception e) { System.err.printf("获取token失败!"); e.printStackTrace(System.err); } return null; } }
其中clientId和clientSecret为你注册机器人后获得的API Key / Secret Key。
2.UnitService
package com.ssx.robot.baidu; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * 重要提示代码中所需工具类 * FileUtil,Base64Util,HttpUtil,GsonUtils请从 * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 * 下载 */ public class UnitService { /*sessionid和msg用户的话*/ public static Map<String, String> utterance(String session_id, String content) { Map<String, String> map = new HashMap<String, String>(); try { String talkUrl = "https://aip.baidubce.com/rpc/2.0/unit/service/chat"; // 请求参数 scene_id记得修改 //{"log_id":"UNITTEST_10000","version":"2.0","service_id":"S27823","skill_id":"","session_id":" ","request":{"query":"","user_id":"UNIT_DEV_11"}} String params = "{\"log_id\":\"UNITTEST_10000\",\"version\":\"2.0\",\"service_id\":\"S27823\",\"session_id\":\"" + session_id + " \",\"request\":{\"query\":\"" + content + "\",\"user_id\":\"UNIT_DEV_11\"}}"; String accessToken = AuthService.getAuth(); //获得返回的json数据 String str = HttpUtil.post(talkUrl, accessToken, "application/json", params); System.out.println(str); System.out.println("=========str已获得========"); //获得result JSONObject jsonobject = JSONObject.fromObject(str); String result = jsonobject.getString("result"); System.out.println(result); System.out.println("======result已获得======"); //获得会话session_id JSONObject jsonobject2 = JSONObject.fromObject(result); session_id = jsonobject2.getString("session_id"); System.out.println("======sessionid:====" + session_id); map.put("session_id", session_id); //获得动作列表 JSONArray response_list = jsonobject2.getJSONArray("response_list"); // JSONArray response_list2 = JSONObject.fromObject(response_list); System.out.println("===response_list===:" + response_list); if (response_list.size() > 0) { for (int i = 0; i < response_list.size(); i++) { JSONObject test = response_list.getJSONObject(i); JSONArray action_list = test.getJSONArray("action_list"); JSONObject action_list1 = JSONObject.fromObject(action_list.get(0)); System.out.println("====循环action_list====" + action_list1); String say = ""; if (!action_list1.get("type").toString().equals("failure")) { say = (String) action_list1.get("say");//机器bot返回的话术 map.put("say", say);//循环插入覆盖,但每次调用都不同所以依然是随机的 } System.out.println("======say:====" +map.get("say")); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } public static void main(String[] args) { utterance("", "你好"); } }
一些其他工具类在注释中可以下载。因为是单论对话所以我session_id就设置为空了,content就是我们用户输入的话了。params是要传上去的数据内容是json字符串,我写的是一些必要的属性(talkUrl可以是机器人也可以是技能api,因此params也会相应不同)。然后我只传了say,也就是机器人回的话,因为偷懒。。。
控制类:
@RequestMapping("/unit") public void unitchat(HttpServletRequest request, HttpServletResponse response) throws Exception { //防乱码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); JSONObject data = new JSONObject(); Gson gson = new Gson(); String msg = request.getParameter("msg"); //调用unit分析语义 Map<String, String> map = UnitService.utterance("", msg); String say = gson.toJson(map.get("say")); data.put("say", say); HttpUtils.send(response, data.toString()); }
获取前端传的msg并传回机器人的say
前端:
$.ajax({ url: _ctx + "/unit", data: { "msg":txti }, type: "post", dataType: "json", async: true, success: function (data) { var say = JSON.parse(data.say); $('#sended').append('<div id="left"><div id="txt">' + say + '</div></div>'); document.getElementById('sended').scrollTop = document.getElementById('sended').scrollHeight; } });
ajax调用并显示
大概就这些啦