Friday, 4 October 2019

Post 75: Fetching data from Android app

Sometimes you want to fetch data from an API on some webserver from your Android app. Let say the server's adress is http://my-requested-data.com and let's say it returns you data in json format. This is how you do it:

        String url = "http://my-requested-data.com/?format=json";
       
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //Read JSON response and print
        JSONObject myResponse = new JSONObject(response.toString());
//Access node from the json object:
        float finalResult = Float.parseFloat(myResponse.getString("some_predicate"));

No comments:

Post a Comment

Tweet