本人在使用圖靈機器人的過程當中,發現很不錯,想試了經過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;//返回消息 }