聊天机器人实现原理
程序员文章站
2022-07-02 23:20:51
...
后端调用API:
package com.mychat.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 机器人聊天
*/
public class CharServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String APIKEY = "7d14fa4bc295404a9fced576c37453e5"; //图灵机器人的apikey
String question = request.getParameter("id");//用户输入的问题inputValue
System.out.println(question);
String INFO = URLEncoder.encode(question, "utf-8");
String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
URL getUrl = new URL(getURL);
HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
// 断开连接
connection.disconnect();
PrintWriter out = response.getWriter();
System.out.println(sb.toString());
out.println(sb.toString());
out.close();
}
}
前端页面展示:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>聊天助手</title>
<script src="js/jquery-1.8.3.min.js"></script>
<link rel="stylesheet" href="css/chat.css">
<link rel="alternate icon" href="assets/i/favicon.ico">
<link rel="stylesheet" href="assets/css/amazeui.min.css">
<link rel="stylesheet" href="assets/css/app.css">
<link href="umeditor/themes/default/css/umeditor.css" rel="stylesheet">
<style>
* {
margin: 0;
padding: 0;
}
.chat-content-container {
height: 49rem;
overflow-y: auto;
border: 1px solid silver;
}
.container{
border: 1px solid #cdcaca;
padding:0px 0px;
}
.am-u-sm-6{
left:0px;
}
.am-u-sm-push-6{
width:100%;
}
</style>
<script>
/*自定义时间格式*/
Date.prototype.Format = function (fmt) { // author: meizz
var o = {
"M+": this.getMonth() + 1, // 月份
"d+": this.getDate(), // 日
"h+": this.getHours(), // 小时
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
window.onload=function(){
$(".arrow").hide();
$(".arrows").hide();
}
document.onkeydown = function(e) {
if (e.keyCode == 13 && e.ctrlKey) {
// 这里实现换行
document.getElementById("sendContent").value += "\n";
} else if (e.keyCode == 13) {
// 避免回车键换行
e.preventDefault();
// 下面写你的发送消息的代码
f();
}
}
function fc(){
window.location.href="friend.jsp"
}
function f() {
var isSelf=true;
var name=$('#nickname').val()
var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
var cnt = $("#sendContent").val();
if(cnt == '')alert('内容不能为空');
if(cnt != ''){
var messageItem = '<li class="am-comment '
+ (isSelf ? 'am-comment-flip' : 'am-comment')
+ '">'
+ '<a href="javascript:void(0)" ><img src="assets/images/'
+ (isSelf ? 'self.jpg' : 'others.jpg')
+ '" alt="" class="am-comment-avatar" width="48" height="48"/></a>'
+ '<div class="am-comment-main"><header class="am-comment-hd"><div class="am-comment-meta">'
+ '<a href="javascript:void(0)" class="am-comment-author">'
+ name + '</a> <time>' + time
+ '</time></div></header>'
+ '<div class="am-comment-bd">' + cnt
+ '</div></div></li>';
$(messageItem).appendTo('#message-list');
$('#sendContent').val('')
// 把滚动条滚动到底部
$(".chat-content-container").scrollTop($(".chat-content-container")[0].scrollHeight);
isSelf=false;
name="小埋"
$.ajax({
data : cnt,
type : "post",
url : "CharServlet?id=" + encodeURIComponent(cnt),
contentType: "application/json;charset=utf-8",
dataType : "json",
success : function(msg) {
var messageItem = '<li class="am-comment '
+ (isSelf ? 'am-comment-flip' : 'am-comment')
+ '">'
+ '<a href="javascript:void(0)" ><img src="assets/images/'
+ (isSelf ? 'self.jpg' : '1.jpg')
+ '" alt="" class="am-comment-avatar" width="48" height="48"/></a>'
+ '<div class="am-comment-main"><header class="am-comment-hd"><div class="am-comment-meta">'
+ '<a href="javascript:void(0)" class="am-comment-author">'
+ name + '</a> <time>' + time
+ '</time></div></header>'
+ '<div class="am-comment-bd"><a id="myurl" href="#">' + msg.text+'</a>'
+ '</div></div></li>';
$(messageItem).appendTo('#message-list');
if(msg.url!=null)
document.getElementById("myurl").href = msg.url;
// 把滚动条滚动到底部
$(".chat-content-container").scrollTop($(".chat-content-container")[0].scrollHeight);
},
error : function(msg) {
alert("请求失败");
}
});
}
}
</script>
</head>
<!-- 聊天内容框开始 -->
<div class="am-container container" >
<div class="am-u-sm-12" style="background:#dcad50;">
<!-- <div class="am-u-sm-3 am-u-sm-push-6"> -->
<h3 style="text-align:center;margin-top:auto;margin-bottom:auto;padding:3px 0px;font-size:20px">聊天机器人</h3>
<!-- </div> -->
</div>
<div class="chat-content-container">
<div class="am-u-sm-6 am-u-sm-push-6">
<ul id="message-list" class="am-comments-list am-comments-list-flip"></ul>
</div>
</div>
<!-- </div> -->
<!-- 聊天内容框结束 -->
<div class="message-input am-margin-top">
<!-- 输入内容框开始 -->
</div>
<div class="border-img"></div>
<textarea id="sendContent" style="width:100%; height:19rem;"></textarea>
<!-- 输入昵称框开始 -->
<!-- <div class="am-g am-g-fixed am-margin-top"> -->
<div class="am-u-sm-6" style="display: none;">
<div id="message-input-nickname" class="am-input-group am-input-group-primary">
<span class="am-input-group-label"><i class="am-icon-user"></i></span>
<input id="nickname" type="text" class="am-form-field" value="${user.name}"/>
</div>
</div>
<div class="am-u-sm-12">
<p style="text-align:right;margin:0px">
<button onclick="fc()" class="am-btn am-btn-warning">
关闭
</button>
<button id="send" onclick="f()" type="button" class="send am-btn am-btn-primary">
<i class="am-icon-send"></i>发送
</button>
</p>
</div>
</div>
</body>
</html>
页面设计css部分就不粘贴上去了,有问题私聊吧!
下一篇: 聊天机器人