最近又用java写了云小蜜的调用教程,这里总结一下,首先maven依赖为:
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-chatbot -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-chatbot</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.3</version>
</dependency>
然后调用代码为:
package services;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import java.util.*;
import com.aliyuncs.chatbot.model.v20171011.*;
public class ChatbotDemo {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai(你的云小蜜的区域)", "your id", "your secret");
IAcsClient client = new DefaultAcsClient(profile);
ChatRequest request = new ChatRequest();
request.setUtterance("电脑电脑死机了怎么办");
request.setInstanceId("你创建的云小蜜的id");
try {
ChatResponse response = client.getAcsResponse(request);
List<ChatResponse.Message> list_messages=response.getMessages();
String content="";
for (ChatResponse.Message message:list_messages
) {
String type=message.getType();
System.out.println(type);
if(type.equals("Recommend")){
List<ChatResponse.Message.Recommend> list_recommends=message.getRecommends();
content+="您可以这样问:\n";
for (ChatResponse.Message.Recommend recommend:list_recommends) {
content+=recommend.getTitle()+'\n';
}
}else if(type.equals("Text")){
String text=message.getText().getContent();
content+=text;
}else if(type.equals("Knowledge")){
String text=message.getKnowledge().getSummary();
content+=text;
}
}
System.out.println(content);
System.out.println(new Gson().toJson(response));
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
System.out.println("ErrCode:" + e.getErrCode());
System.out.println("ErrMsg:" + e.getErrMsg());
System.out.println("RequestId:" + e.getRequestId());
}
}
}
然后就成功了啊,官方的sdk真是强大。结果:
Knowledge
亲,先尝试重启,若重启后仍然死机,请到IT服务台报修,IT管理员会根据检测情况处理哦。
{"requestId":"AD3F164E-1999-4CF6-9314-E354D5710ED8","sessionId":"ce59204c4da14ff4873352d3bd18992d","messageId":"13aa3a4052f4463aad6fa4e24943f4fb","messages":[{"type":"Knowledge","recommends":[],"text":{},"knowledge":{"id":"74944","title":"电脑电脑死机了怎么办","summary":"亲,先尝试重启,若重启后仍然死机,请到IT服务台报修,IT管理员会根据检测情况处理哦。","content":"亲,先尝试重启,若重启后仍然死机,请到IT服务台报修,IT管理员会根据检测情况处理哦。","answerSource":"KnowledgeBase"}}]}
Process finished with exit code 0
参考文献
[1].Aliyun Java SDK ChatBot. https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-chatbot/1.0.0
[2].Java 调用阿里云小蜜示例代码. https://blog.csdn.net/u010651369/article/details/81743472
[3].OPEN API Explorer