Consuming Web Services Using HTTP-Consuming JSON Services

What is Consuming Web Services in Android?

Consuming web services means that your Android app connects to a remote server (API), fetches data (usually in JSON format), and displays it in the UI.
Example Use Cases:
Fetching weather updates
Displaying news articles
Fetching stock prices
User login & authentication

Steps to Consume Web Services in Android (JSON Example)

  1. Make an HTTP request (GET) to an API
  2. Receive JSON response from the server
  3. Parse JSON data in Java
  4. Update UI with the data

Example: Fetching JSON Data from an API

We will create an Android app that fetches random user data from the API URLhttps://randomuser.me/api/ We will extract name and email from the user data and display them in a TextView.
Expected JSON Response:

{
  "results": [
    {
      "name": {
        "first": "John",
        "last": "Doe"
      },
      "email": "johndoe@example.com"
    }
  ]
}

Add Internet Permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

XML Layout (activity_main.xml)

A simple UI with a Button and TextView to show the fetched data

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <Button
        android:id="@+id/btnFetch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fetch Data" />

    <TextView
        android:id="@+id/textViewResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:paddingTop="20dp"/>
</LinearLayout>

Java Code (MainActivity.java)

Using HttpURLConnection to fetch JSON from API

public class MainActivity extends AppCompatActivity {

    private TextView textViewResult;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnFetch = findViewById(R.id.btnFetch);
        textViewResult = findViewById(R.id.textViewResult);

        btnFetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new FetchData().execute();
            }
        });
    }

    private class FetchData extends AsyncTask<Void, Void, String>{

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL("https://randomuser.me/api/");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                reader.close();
                return result.toString();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        protected void onPostExecute(String result) {
            if (result != null) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray resultsArray = jsonObject.getJSONArray("results");
                    JSONObject user = resultsArray.getJSONObject(0);
                    JSONObject name = user.getJSONObject("name");

                    String firstName = name.getString("first");
                    String lastName = name.getString("last");
                    String email = user.getString("email");

                    textViewResult.setText("Name: " + firstName + " " + lastName + "\nEmail: " + email);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Explanation (Simple Terms)

  1. When the user taps the button, FetchData runs in the background.
  2. It makes an HTTP request to https://randomuser.me/api/
  3. Reads the JSON response and extracts "name" and "email".
  4. Updates the TextView with the fetched data.