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 : The first step in consuming a web service in Android is to make an HTTP request to an API. In most cases, this will be a GET request where you are asking the server to send you some data (for example, a list of items in JSON format). To make this request, you can use several libraries available in Android, but HttpURLConnection (the native Java library) or third-party libraries like Retrofit, OkHttp, or Volley are commonly used.
  2. Receive JSON response from the server: Once you send the GET request, the server will respond with some data. In most cases, this data will be in JSON format, especially when dealing with RESTful APIs. JSON is a popular format for APIs because it is lightweight and easy to parse.
  3. Parse JSON data in Java: Once the JSON response is received, the next step is to parse it. Android provides built-in tools like org.json.JSONObject and org.json.JSONArray classes to handle JSON parsing.
  4. Update UI with the data: Finally, after you have successfully parsed the JSON data, the next step is to update the UI of your app with the results (e.g., displaying a list of people). In Android, UI updates must be performed on the main thread, so you can’t directly update the UI from a background thread. To solve this, you can use an AsyncTask, Handler, or, more commonly nowadays, LiveData and ViewModel for managing UI updates in a clean and efficient way.

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.