前言:目前隻寫了一個簡單的Demo,圖形界面還未寫
一 簡單介紹以及apikey擷取
就我個人而言,目前有兩個API是比較不錯的,一個是百度的接口,另一個是圖靈機器人(http://www.tuling123.com/)的接口。前者調用簡單,而且沒有使用次數限制(PS:據說還是有限制?);後者需要進行一系列身份認證,而且每天次數限制是5000(PS:貌似可以免費增加次數),但是它的優勢是可以進行個性化設定,這點比較好。
在這裡為了友善示範,我使用百度的接口進行測試,申請位址是:http://apistore.baidu.com/apiworks/servicedetail/736.html 可以看到,請求參數有三個,分别是:key,info,userid,其中key和userid用預設值就可以了。當然最重要的是要在請求的header裡添加上apikey這一項,點選這裡就可以免費擷取了:注:要是對Java網絡程式設計不是很熟悉的話,可以參考下方的Demo
二 一個簡單的Demo
package action;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TuringRobot {
public static void main(String[] args) {
TuringRobot turing = new TuringRobot();
String question = "北京天氣";
String temp = turing.getResponse("879a6cb3afb84dbf4fc84a1df2ab7319","您自己的apikey", question, "eb2edb736");
System.out.println("小圖:" + temp);
String temp2 = turing.getResponse("879a6cb3afb84dbf4fc84a1df2ab7319","您自己的apikey", "你這麼可愛,一定是個男孩子", "eb2edb736");
System.out.println("小圖:" + temp2);
}
/**
* 使用百度圖靈機器人,擷取回答
*
* @param key 預設值:879a6cb3afb84dbf4fc84a1df2ab7319
* @param ApiKey 在APIStore調用服務所需要的API密鑰,申請位址:http://apistore.baidu.com
* @param info 想要請求的問題
* @param userid 使用者id 預設值:eb2edb736
*
* @return 擷取的回複
* */
public String getResponse(String key,String ApiKey,String info,String userid){
String httpUrl = "http://apis.baidu.com/turing/turing/turing?";
// try {
// info = URLEncoder.encode(info,"UTF-8"); //URL編碼,可以不加
// } catch (UnsupportedEncodingException e1) {
// e1.printStackTrace();
// }
String httpArg = "key=" + key + "&info=" + info + "&userid=" + userid;
try {
URL url = new URL(httpUrl + httpArg);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("apikey", ApiKey);
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
String line = "";
String reg = "\"text\":\"(.*)?\",\"code\"";
Pattern pattern = Pattern.compile(reg);
Matcher matcher;
while((line = reader.readLine()) != null){
matcher = pattern.matcher(line);
if(matcher.find())
return matcher.group(1);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}