本人在使用图灵机器人的过程当中,发现很不错,想试了经过api请求来获取回复,这样能够作一个页面聊天仍是很不错的。网上搜到的文章好多都是get接口,如今已经不能用了,也不用urlencodeer方法处理info信息了。通过尝试,终于成功,分享方法代码,供你们参考。java
目前图灵已经取消了非认证免费用户的请求次数。 如今httpclient自带的EntityUtils解析响应效果很是好,例子代码有点老了。编程
public static String getReplyFromRobot(String text) throws JSONException, ClientProtocolException, IOException { String url = "http://www.tuling123.com/openapi/api";//设置访问接口地址 CloseableHttpClient httpClient = HttpClients.createDefault();//建立并实例化链接 JSONObject jsonObject = new JSONObject();//建立并实例化jsonobject jsonObject.put("key", "915b34e69c0371");//输入key jsonObject.put("info", text);//输入信息 // jsonObject.put("loc", "北京市中关村");//设置地点 jsonObject.put("userid", "915b34e41cb351c0371");//设置用户id String arguments = changeJsonToArguments(jsonObject);//将json数据转化为参数 HttpPost httpPost = new HttpPost(url+arguments);//请求post接口 HttpResponse response = httpClient.execute(httpPost);//获取响应 InputStream inputStream = response.getEntity().getContent();//建立并实例化字节输入流,使用响应实体做为输入流 InputStreamReader reader = new InputStreamReader(inputStream, "utf-8");//建立并实例化字符输入流,并设置编码格式 StringBuffer buffer = new StringBuffer(" ");//建立并实例化stringbuffer,存放响应信息 char[] buff = new char[512];//建立并实例化字符数组 int length = 0;//声明变量length,表示读取长度 while ((length = reader.read(buff)) != -1) {//循环读取字符输入流 String x = new String(buff, 0, length);//获取读取到的有效内容 System.out.println(x);//输出内容 buffer.append(x);//将读取到的内容添加到stringbuffer中 } JSONObject dsa = new JSONObject(buffer.toString().trim());//将响应结果转化为jsonobject String message = dsa.getString("text");//获取返回消息 return message;//返回消息 }