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)
- Make an HTTP request (GET) to an API
- Receive JSON response from the server
- Parse JSON data in Java
- 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 URL → https://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)
- When the user taps the button,
FetchData
runs in the background. - It makes an HTTP request to
https://randomuser.me/api/
- Reads the JSON response and extracts
"name"
and"email"
. - Updates the
TextView
with the fetched data.