๐Ÿš€ author: “Big Data Zen”

๐Ÿš€ article introduction: recently, a friend left a message, “No one has talked to me for a long time, can I write a chat robot to show the romance of programmers?” , small zen: “arrangement!”

๐Ÿš€ follow me: follow me to learn, exchange, information sharing oh.

๐Ÿš€ Welcome to like ๐Ÿ‘, collect โญ, leave a message ๐Ÿ’ฌ


1. Intelligent chat robot demonstration

Artificial intelligence has been a hot topic recently, but the application field of automatic artificial intelligence has been expanding, and artificial intelligence will continue to be popularized and applied in people’s life in the future. The chatbot in this post, written in Java, can respond intelligently to your messages, which is quite an interesting gadget. The final result is shown below

2. Introduction to intelligent Q&A platform API

The chat robot project uses the intelligent API of Qingyun Class to get information feedback by calling the API.

The specific call format is as follows:

http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s the % s to we need to send to the content of the robot, can get the result of the API call feedback.Copy the code
  • Key Specifies the free parameter
  • Appid is set to 0 for intelligent identification
  • MSG is the search keyword
  • Result indicates the returned status. 0 indicates that the status is normal
  • Content Indicates the content of the information returned by the API

You can see that the data is returned as JSON.

3. Integrate third-party JSON open source libraries

Gson is a class library provided by Google, which can be used to process the mapping between Java objects and JSON data, converting a JSON string into a Java object, which is convenient for us to process the JSON data returned by API. The following shows how to import the Gson class library into our project.

First of all, you can go to the official website to download the corresponding JAR package, or directly private message me to obtain. After obtaining the JAR package to find a full English path to save. The editor we use here is IDEA, so we use IDEA for demonstration. If you use other editors, the import method will be similar. Open the following interface in IDEA and import the JAR package.

4. Intelligent robot project framework building and module division

Project setup: The setup part doesn’t require much, just create a new normal Java project using IDEA

Project module construction:

  • The Model class is used to hold the objects returned by the request
  • The util class is used to hold utility classes used by projects, such as HTTP request parsing classes
  • The App class is used as an entry point for robotics projects
  • The Service class is used to implement the interface to the business

The two related entity classes are as follows:

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; } } 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; }}Copy the code

5. Encapsulate a robot HTTP tool class

The HTTP utility class is mainly used to request the API and get the returned content

public class HttpUtils { public static String request(String api){ HttpURLConnection connection = null; int responseCode = 0; try{ URL url = new URL(api); 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; }}Copy the code

6. Realize the interface and definition of robot Service layer

Implement the robot interface layer

โ€‹
public interface RobotService {
โ€‹
 ย  ย Response qa(String msg) ;
โ€‹
}
Copy the code

Implement the robot interface implementation class, which implements the API’s request and returns the result as an entity class

public class QkyRobotServiceImpl implements RobotService { 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") ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String result = HttpUtils.request(api); Response Response = gson.fromjson (result, response.class); return response; }}Copy the code

7. Make your own robot portal

Write the main class of the entry, and call the encapsulated module to write the main class of the robot entry

public class Main { private static final RobotService robotService = new QkyRobotServiceImpl(); public static void main(String[] args)throws Exception { Scanner scanner = new Scanner(System.in); System.out.println(" dear C station boss, please give me a loud name!!" ); System.out.println("-------------------------------"); String name = scanner.nextLine(); System.out.println(" hello, BIG data, I am a robot in small Zen blog, directly give me instructions oh ~"); System.out.println("-------------------------------"); while (true){ String input = scanner.nextLine(); If (" 88 ". EqualsIgnoreCase (input)) {System. Out. Println (" welcome next time, bye bye "); break; }else { Response response = robotService.qa(input); if(response ! = null && response.getCode() == 0){ System.out.println("-------------------------------"); System.out.println(name+":"+ new String(response.getContent().getBytes(),"UTF-8")); System.out.println("-------------------------------"); }else {system.out.println (name+": ");}else {system.out.println (name+": "); } } } scanner.close(); }}Copy the code

8. Pack your robot for use

In order to facilitate our use of the project, we use IDEA to package the project into JAR packages. By following these steps, we can package all the modules and libraries in our project, and use the java-jar jar name when we need to call it.

9. To summarize

Our robot project is complete after packing. I hope you can learn something from this blog. ๐Ÿ’ช