teja2495
10/4/2018 - 12:59 AM

Get API Data (basic approach)

StringBuilder getAPIData(String strUrl) {
    StringBuilder result = new StringBuilder();
    HttpURLConnection connection = null;
    try {
        URL url = new URL(strUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = r.readLine()) != null) {
                result.append(line).append('\n');
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
    return result;
}

//to convert string builder to string using toString() method.