1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
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密钥,申请地址:https://apistore.baidu.com * @param info 想要请求的问题 * @param userid 用户id 默认值:eb2edb736 * * @return 获取的回复 * */ public String getResponse(String key,String ApiKey,String info,String userid){ String httpUrl = "https://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 "" ; } } |