首先要在图灵机器人官网注册(http://www.tuling123.com)一个帐号,新帐号可以免费创建一个机器人并且拥有自己的apikey,虽然功能有限制,但是简单的使用还是很赞的。
图灵机器人提供了多种多样的外部接口,这里使用Web API v2.0接口来进行开发,相对web API v1.0支持更多的输入格式。具体的使用介绍请参照官网文档https://www.kancloud.cn/turing/web_api/522992
最终的运行结果如下:
具体实现代码如下,代码比较简单,不做过多解释了。
package com.wcf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class Chatbot {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url="http://openapi.tuling123.com/openapi/api/v2";
String question="";
String apikey="d38891d7ab524688919dce4f3a95abbd";
String userID="001";//任意值,如果用于微信平台开发,建议使用微信粉丝的userID作为此值
@SuppressWarnings("resource")
Scanner scanner=new Scanner(System.in);
while((question=scanner.nextLine()) != null)
{
String data="{\"perception\": {\"inputText\": {\"text\": \""+question+"\"}},\"userInfo\": {\"apiKey\": \""+apikey+"\",\"userId\": \""+userID+"\"}}";
try {
String response=sendPost(url,data);
JSONObject jsonObject=JSON.parseObject(response);
//这里仅仅提取出了文本答案,如果需要其他答案请自行修改代码
System.out.println(jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("values").getString("text"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String sendPost(String url,String Params)throws IOException{
OutputStreamWriter out = null;
BufferedReader reader = null;
String response="";
try {
URL httpUrl = null; //HTTP URL类 用这个类来创建连接
//创建URL
httpUrl = new URL(url);
//建立连接
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("connection", "keep-alive");
conn.setUseCaches(false);//设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//POST请求
out = new OutputStreamWriter(
conn.getOutputStream());
out.write(Params);
out.flush();
//读取响应
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
response+=lines;
}
reader.close();
// 断开连接
conn.disconnect();
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return response;
}
}