封装工具类
封装工具类 package utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * 图灵机器人api工具类 * @author admin * */ public class TuLingApiUtil { //自己的apikey,注意不是密钥 图灵接口的 private static final String key = "自己的KEY"; public static String getResult( String content ) { //青云客网络api接口 这个不需要定义Key //String apiUrl = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=";
//图灵api接口 String apiUrl = "http://www.tuling123.com/openapi/api?key="+key+"&info="; try { //内容需要utf-8编码(官方文档中有说明) content = URLEncoder.encode(content, "utf-8"); //拼接url apiUrl = apiUrl + content; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //封装请求头 HttpGet request = new HttpGet(apiUrl); String result = ""; try { //发送http请求 HttpResponse response = HttpClients.createDefault().execute(request); //获取响应码 int code = response.getStatusLine().getStatusCode(); if (code == 200) { //获取返回的结果 result = EntityUtils.toString(response.getEntity()); } else { System.out.println("code=" + code); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //返回结果 return result; } }
控制器写法
private R message(String message){ String msg = URLEncoder.encode(message, "GBK"); String gbk = URLDecoder.decode(msg, "GBK"); while (true){ //接收返回的结果 String result = TuLingUtil.getResult(gbk); return R.ok(result); } }
本地控制台测试一下
public class TestApi { public void test() { Scanner sc = new Scanner(System.in); while(true) { String content = ""; //控制台输入信息 content = sc.nextLine(); //接收返回的结果 String result = TuLingApiUtil.getResult(content); //把json格式的字符串转化为json对象 JsonObject json = new JsonParser().parse(result).getAsJsonObject(); //获得text键的内容,并转化为string String back = json.get("text").toString(); //打印结果 System.out.println(back); } } }
标签:result,http,String,content,Java,api,聊天,import,在线 From: https://www.cnblogs.com/dsds/p/16756426.html