java开发人工智能问答小项目

一、前置知识补充

1.如何发起http请求,获取云服务端的响应数据

复制代码
package net.xdclass.chapter15;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLTest {

    public static void main(String []args) throws Exception {

        URL url = new URL("https://assets.msn.cn/breakingnews/v1/cms/api/amp/article/AA5Quct");//请求数据的地址

        System.out.println("getHost="+url.getHost());
        System.out.println("getProtocol="+url.getProtocol());
        System.out.println("getPort="+url.getPort());
        System.out.println("getPath="+url.getPath());
        System.out.println("getQuery="+url.getQuery());
        //getPath和getQuery的组合
        System.out.println("getFile="+url.getFile());

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//打开连接

       int responseCode = httpURLConnection.getResponseCode();//获取响应码
       if(200 <= responseCode && responseCode<=299){//正常响应

           try(InputStream inputStream = httpURLConnection.getInputStream();//获取输入流
               BufferedReader in =  new BufferedReader(new InputStreamReader(inputStream))){//读云服务端响应的数据

             StringBuilder response = new StringBuilder();//创建builder容器对象,存储拼接后的响应数据

             String currentLine;

             while ( (currentLine =in.readLine())!=null ){
                 response.append(currentLine);//拼接数据,形成完整的响应数据
             }

            System.out.println(response.toString());

           }catch (Exception e){
               e.printStackTrace();
           }

       }



    }
}

2.将获取数据格式化

  • 在线工具

JSON在线解析格式化验证 - JSON.cn

花括号表示对象,方括号表示数组

下载json库,为本地项目配置解析工具

  • 常见的JSON库

Gson Google公司开源 地址:https://github.com/google/gson

FastJson阿⾥里里巴巴开源 地址:https://github.com/alibaba/fastjson

引入后测试运行:

复制代码
package net.xdclass.chapter15;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class URLTest {

    public static void main(String []args) throws Exception {

        URL url = new URL("https://assets.msn.cn/breakingnews/v1/cms/api/amp/article/AA5Quct");

        System.out.println("getHost="+url.getHost());
        System.out.println("getProtocol="+url.getProtocol());
        System.out.println("getPort="+url.getPort());
        System.out.println("getPath="+url.getPath());
        System.out.println("getQuery="+url.getQuery());
        //getPath和getQuery的组合
        System.out.println("getFile="+url.getFile());

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//打开连接

       int responseCode = httpURLConnection.getResponseCode();//获取响应码
       if(200 <= responseCode && responseCode<=299){//正常响应

           try(InputStream inputStream = httpURLConnection.getInputStream();//获取输入流
               BufferedReader in =  new BufferedReader(new InputStreamReader(inputStream))){//读云服务端响应的数据

             StringBuilder response = new StringBuilder();//创建builder容器对象,存储拼接后的响应数据

             String currentLine;

             while ( (currentLine =in.readLine())!=null ){
                 response.append(currentLine);//拼接数据,形成完整的响应数据
             }

            String jsonStr=response.toString();//响应内容
               System.out.println(jsonStr);
             Gson gson = new Gson();//创建gson对象
              Map<String,Object> objectmap=gson.fromJson(jsonStr, Map.class);//将json字符串转换成map对象
               Object title = objectmap.get("title");//获取title的值
               System.out.println(title);

           }catch (Exception e){
               e.printStackTrace();
           }

       }



    }
}

2.搭建一个echo服务

复制代码
package net.xdclass.chapter15;

import java.util.Scanner;

public class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);//创建扫描器对象
        while(true){
            System.out.println("请输入一个字符:");
            String context = scanner.nextLine();//获取用户输入的内容
            if("886".equalsIgnoreCase(context)){
                System.out.println("欢迎下次登录,再见!");
                break;
            }else{
                System.out.println("您输入的内容是:"+context);
            }
        }
        scanner.close();//关闭扫描器
    }
}

3.智能问答API平台的搭建

青云客智能聊天机器人API

使用

http://api.qingyunke.com/api.php?key=free&appid=0&msg=输入你想了解的内容​​​​​​

eg: api.qingyunke.com/api.php?key=free&appid=0&msg=你今年多大了

二、项目的正式开发

1..项目基本框架搭建

流程

用户输⼊入指令 -> http发送请求 -> 解析结果 -> 显示内容 -> 循环上述操作

包分层

model 存放请求响应对象

util 存放工具类

app main函数入口

service 相关业务接口和实现类

2.引入json依赖

本地引入Json库:第一点中有说明。

3.model层

初始请求参数

复制代码
package model;

public class Request {
    //初始化请求参数
    private String key = "free";

    private String appid = "0";

    private String msg = "";


    public Request(){}


    public Request(String msg){
        this.msg = msg;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

初始响应参数

复制代码
package model;

public class Response {
    //初始化响应参数
    private int code;

    private String content;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

4.封装Http工具类

复制代码
package util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {


    public static String request(String api ){//访问的静态方法

        HttpURLConnection connection = null;//连接对象
        int responseCode = 0;//响应码
        try{
            URL url = new URL(api);//获取api的URL对象
            //获取对应的连接对象
            connection = (HttpURLConnection) url.openConnection();
            responseCode = connection.getResponseCode();//获取连接的响应码
        }catch (Exception e){
            e.printStackTrace();
        }

        if(200 <= responseCode && responseCode<=299){//正常响应
            try(InputStream inputStream = connection.getInputStream();//获取输入流
                BufferedReader in =  new BufferedReader(new InputStreamReader(inputStream));//读取输入流中的内容
            ){

                StringBuilder response = new StringBuilder();//创建一个字符串对象,用于存储响应内容
                String currentLine;

                while ((currentLine = in.readLine())!= null){//逐行读取内容
                    response.append(currentLine);
                }

                String result = response.toString();
                return result;

            }catch (Exception e){
                e.printStackTrace();
            }


        }

        return null;


    }

}

5.service业务层接口的定义与实现

接口

复制代码
package service;

import model.Response;

import java.io.UnsupportedEncodingException;

//定义一个业务服务接口
public interface RobotService {

    Response qa(String msg) ;//问答接口传入请求的内容,返回响应的内容

}

对应实现类

复制代码
package service;

import com.google.gson.Gson;
import model.Response;
import util.HttpUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

//实现业务服务接口
public class QkyRobotServiceImpl implements RobotService {


    //青云客api
    private static final String apiTpl = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s";


    private static  final Gson gson = new Gson();



    @Override
    public Response qa(String msg) {

        String api = null;
        try {
            api = String.format(apiTpl, URLEncoder.encode(msg,"UTF-8") );//拼接请求的url
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String result =  HttpUtils.request(api);//通过Http工具类来发送请求

        //可以做逻辑判断,比如null的时候,或者出错

        Response response = gson.fromJson(result,Response.class);//将json字符串转化为Response对象

        return response;
    }


}

6.实现核心入口类app main层

获取用户输入,调用请求方法

复制代码
package app;

import model.Response;
import service.AliyunRobotServiceImpl;
import service.QkyRobotServiceImpl;
import service.RobotService;

import java.util.Scanner;

public class Main {

    //定义请求实现类对象
    private static final RobotService robotService = new QkyRobotServiceImpl();


    public static void main(String[] args)throws Exception {
        //1.获取用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("老板,麻烦您给我取个响亮的名称,按回车键确定!!!!");
        String name = scanner.nextLine();
        System.out.println("hi,我是您的小助手 "+name +", 直接对我下达指令");
        //2.对不同输入作处理
        while (true){

            String input = scanner.nextLine();
            if("886".equalsIgnoreCase(input)){
                System.out.println("欢迎下次使用,拜拜");
                break;
            }else {
              Response response = robotService.qa(input);//通过对象调用请求服务方法


              if(response != null && response.getCode() == 0){//响应正常
                  System.out.println(name+":"+ new String(response.getContent().getBytes(),"UTF-8"));
              }else {
                  System.out.println(name+": 暂时没明白您的意思,重新告诉我下吧");
              }
            }

        }
        scanner.close();


    }
}

7.项目打包

jar包方式

File -> Project Structure -> artifacts -> + -> jar -> from modules-> 选主类和第⼀一个单向按钮-》确定后会生成Manifest文件

勾选include in project build(不用)

菜单栏 build->build artifacts -> build java -jar xxx.jar

启动:在IDEA终端进入out----\artifacts----qa_project_jar再运行

复制代码
java -jar qa-project.jar

8.效果图

源码可以直接去gitee仓库

https://gitee.com/junxin-nanwang​​​​​​​

相关推荐
tt555555555555几秒前
pyQt学习笔记——Qt资源文件(.qrc)的创建与使用
笔记·学习·pyqt
1haooo2 小时前
[计算机三级网络技术]第二章:中小型网络系统总体规划与设计方法
网络·经验分享·笔记·计算机网络·智能路由器
cliff,2 小时前
JavaScript基础巩固之小游戏练习
javascript·笔记·学习
云半S一2 小时前
性能测试笔记
经验分享·笔记·压力测试
齐尹秦3 小时前
HTML5 拖放(Drag and Drop)学习笔记
笔记·学习·html5
sakabu4 小时前
Linux安装MySQL数据库并使用C语言进行数据库开发
linux·c语言·数据库·笔记·mysql·数据库开发
lwewan5 小时前
26考研——图_图的代码实操(6)
数据结构·笔记·考研·算法·深度优先
程序员Linc6 小时前
《数字图像处理》第三章 3.8 基于模糊技术的图像强度变换与空间滤波学习笔记
笔记·学习·数字图像处理·模糊技术·强度变换·空间滤波
vv啊vv7 小时前
使用android studio 开发app笔记
android·笔记·android studio