Java最簡單的調用API接口實例

使用的是最普通的java工程調用圖靈機器人的API(文檔鏈接),人工智障在線聊天。。。。

  1. 首先自行封裝一個post方法(get大體相同)代碼如下:
public class HttpPost {
    /**
     * 向指定 URL 發送POST方法的請求
     *
     * @param httpUrl
     *            發送請求的 URL
     * @param param
     *            請求參數是json
     * @return 所代表遠程資源的響應結果
     */
    public static String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通過遠程url連接對象打開連接
            connection = (HttpURLConnection) url.openConnection();
            // 設置連接請求方式
            connection.setRequestMethod("POST");
            // 設置連接主機服務器超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設置讀取主機服務器返回數據超時時間:60000毫秒
            connection.setReadTimeout(60000);

            // 默認值爲:false,當向遠程服務器傳送數據/寫數據時,需要設置爲true
            connection.setDoOutput(true);
            // 默認值爲:true,當前向遠程服務讀取數據時,設置爲true,該參數可有可無
            connection.setDoInput(true);
            // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            // 設置鑑權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            // connection.setRequestProperty("Authorization", "Bearer
            // da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通過連接對象獲取一個輸出流
            os = connection.getOutputStream();
            // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
            os.write(param.getBytes());
            // 通過連接對象獲取一個輸入流,向遠程讀取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循環遍歷一行一行讀取數據
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 斷開與遠程地址url的連接
            connection.disconnect();
        }
        return result;
    }
}
  1. 根據API文檔封裝調用方法,將參數組裝程接口所需要的json
public class RobotApi {
    private static final String ROBOT_API_HOST = "http://openapi.tuling123.com/openapi/api/v2";
    private String key;
    private String userid;

    public RobotApi(String key, String userid) {
        super();
        this.key = key;
        this.userid = userid;
    }

    private String buildParams(String Word) {
        String a = "{\"reqType\":0,\"perception\": {\"inputText\": {\"text\": \"";
        String b = "\"}},\"userInfo\": {\"apiKey\": \"";
        String c = "\",\"userId\": \"";
        String d = "\"}\r\n" + "}";
        String string = a + Word + b + key + c + userid + d;
        return string;

    }

    public String getRobotResult(String Word) {

        return HttpPost.doPost(ROBOT_API_HOST, buildParams(Word));
    }
}

  1. 最後是主函數(使用阿里的fastjson解析json)
public class Main {
    private static final String apiKey = "自己的key";
    private static final String userId = "自己的id";

    public static void main(String[] args) {
        RobotApi api = new RobotApi(apiKey, userId);
        while (true) {

            Scanner input = new Scanner(System.in);

            String word = input.next();
            String backString = api.getRobotResult(word);

            JSONObject jsonobj = JSON.parseObject(backString);
            JSONArray result = jsonobj.getJSONArray("results");
            for (int i = 0; i < result.size(); i++) {
                System.out.println(result.getJSONObject(0).getJSONObject("values").getString("text"));
            }
        }
    }

}

最後運行效果:

你好
感覺不錯。你好嗎?
北京今天天氣怎麼樣
北京:週一 08月05日,中雨轉雷陣雨 東南風轉東北風,最低氣溫24度,最高氣溫28度。
你叫什麼名字
人見人愛的圖靈機器人,記住了吧~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章