您的位置:首页 > 编程语言 > Java开发

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

2016-04-29 20:07 483 查看
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

/**
 * 第三方接口
 * 
 * @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("");
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  api java