调用第三方api之图灵机器人

来源:互联网 发布:单片机简易密码锁 编辑:程序博客网 时间:2024/05/16 03:54
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

/**
 * 第三方接口
 * ThirdInterface.txt
 * @author Administrator
 *
 */
public class ThirdInterface {
    public static void question(String info) throws IOException {
        URL url = new URL(
                "http://www.tuling123.com/openapi/api?key=026efbd4eda9a99726a1d939fab35acc&info="
                        + URLEncoder.encode(info, "UTF-8"));
        HttpURLConnection httpURLConnection = (HttpURLConnection) url
                .openConnection();
        // 5000如果没有连接,抛出异常
        httpURLConnection.setConnectTimeout(5000);
        // 连续并响应成功
        if (httpURLConnection.getResponseCode() == 200) {
            try (InputStream inputStream = httpURLConnection.getInputStream();
                    Scanner scanner = new Scanner(inputStream);) {
                scanner.hasNext();
                String result = scanner.nextLine();
                System.out.println("answer:"
                        + result.substring(result.indexOf("\":\"") + 3,
                                result.indexOf("\"}")));
            }
        }
    }

    public static void main(String[] args) throws IOException {
        question("");
    }
}
0 0
原创粉丝点击