Java怎样调用api接口,获取返回的Json

Java调用API很简单,主要分为三步:
①找到要调用的API接口
②向指定URL添加参数发送请求
③对返回的字符串进行处理

直接上代码

class HttpRequestUtil {
    //参数直接输入 api的 url
    public static String HttpRequest(String requestUrl) {
        StringBuilder sb = new StringBuilder();
        InputStream ips = getInputStream(requestUrl);
        InputStreamReader isreader = null;
        isreader = new InputStreamReader(ips, StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(isreader);
        String temp = null;
        try {
            while ((temp = bufferedReader.readLine()) != null) {
                sb.append(temp);
            }
            bufferedReader.close();
            isreader.close();
            ips.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //最终返回的是json的string
        return sb.toString();
    }

    //返回输入流
    private static InputStream getInputStream(String requestUrl) {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream in = null;
        try {
            url = new URL(requestUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.connect();
            in = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return in;
    }
}

这里以一言的接口为例:



Last modification:April 4th, 2020 at 09:20 pm
If you think my article is useful to you, please feel free to appreciate