Java使用青云客智能聊天接口做一个小助手

2022-07-27,,,,

文章目录

    • API介绍
    • 演示
    • 代码
      • utils
      • model
      • service
      • main
    • 扩展
    • BUG

API介绍

青云客:http://api.qingyunke.com/

也可以使用其他公司的API,比如百度、腾讯、阿里等。

演示

有点傻。。。。。。。。。。

代码

我把项目分为main、model、service、utils四个包。

  1. main:项目的入口,main()方法所在包。
  2. model:存放响应对象,接收API返回数据。
  3. service:相关业务接口和实现类。
  4. utils:工具类。

utils

HttpUtils类:
网络请求工具类,里面有一个静态方法request(String api),传入API地址,进行网络请求,并返回API返回的数据(json格式)。

package utils;

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

public class HttpUtils {
    /**
     * @param api:API的URL地址
     * @return 请求API所返回的json串
     */
    public static String request(String api) {
        HttpURLConnection httpURLConnection = null;
        int code = 0;//获取HTTP请求状态码
        try {//连接API(需要有网络)
            URL url = new URL(api);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            code = httpURLConnection.getResponseCode();
        } catch (Exception e) {
            return "##出现错误,网络连接异常,请检查网络##";
        }
        if (code >= 200 && code < 300) {//状态码2开头代表成功。
            //建立输入流,获取API返回数据
            try (InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
                 BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                return stringBuilder.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "##出现错误,错误编码##:" + code;
    }
}

http状态码

model

Response类:用于存放API的返回数据。
青云客API返回数据示例:{“result”:0,“content”:“你好,我就开心了”}
result返回状态码,0表示成功,1表示失败。
content返回数据,来自机器人的回答。

package model;

public class Response {
    private String result;//API返回码
    private String content;//API返回数据
    public Response(){}

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getContent() {
        return content;
    }

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

service

RobotService接口:里面有一个方法:Response answer(String question);如果想调用其他平台的问答机器人接口,可以实现此接口。

package service;

import model.Response;

public interface RobotService {
    Response answer(String question);
}

QingYunkeRobotServiceImpl类:青云客平台API的RobotService实现类,里面有一个public Response answer(String question)方法,传入使用者输入的对话,返回Response对象。

package service;

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

import java.net.URLEncoder;

public class QingYunkeRobotServiceImpl implements RobotService {
    //青云客平台的API地址
    private String uri = "https://api.qingyunke.com/api.php?key=free&appid=0&msg=%s";
    private String api;
    Gson gson = new Gson();//用于解析json串

    /**
     * @param question:使用者输入的对话
     * @return Response对象,保存来自机器人的对话
     */
    @Override
    public Response answer(String question) {
        try {
            //需要对输入的对话进行编码,青云客平台使用utf-8编码
            api = String.format(uri, URLEncoder.encode(question, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String ans = HttpUtils.request(api);//获得json串,用字符串储存
        if (!ans.contains("##出现错误,"))
            return gson.fromJson(ans, Response.class);//使用Gson对json串解析,存入Response中
        else {
            Response response = new Response();
            response.setContent(ans);
            return response;
        }
    }
}

main

Main类:程序的入口。

package main;

import model.Response;
import service.QingYunkeRobotServiceImpl;

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //创建青云客的机器人实现类
        QingYunkeRobotServiceImpl qingyunkeRobotService = new QingYunkeRobotServiceImpl();
        Scanner scanner = new Scanner(System.in);
        System.out.println("快给你的小助手取个名字吧,按回车键确定!!!!");
        String name = scanner.nextLine();
        System.out.println("hi,我是您的小助手 " + name + ", 直接对我下达指令");

        while (true) {
            String input = scanner.nextLine();
            //退出条件:用户输入886
            if ("886".equalsIgnoreCase(input)) {
                System.out.println("欢迎下次使用,拜拜");
                scanner.close();
                return;
            }
            Response response = qingyunkeRobotService.answer(input);
            System.out.println(name + ":" + new String(response.getContent().getBytes(), "UTF-8").replace("{br}", "\n"));
        }
    }
}

扩展

可根据不同平台扩充service层的内容,service层主要是调用HttpUtils,传入API的url地址,获取json字符串并解析,得到想要的数据返回。
也可以调用文字转语音接口,让小助手会说话。

BUG

目前有两个bug,一个是+号,转成utf-8后变成了空格,建议使用汉字加。

第二个bug也是转码问题,在打成jar包后运行有部分文字不能正确识别。

本文地址:https://blog.csdn.net/tjk12345/article/details/110132597

《Java使用青云客智能聊天接口做一个小助手.doc》

下载本文的Word格式文档,以方便收藏与打印。