In Android development, consuming web services is a common task. Web services allow your app to interact with external systems, exchange data, and fetch information over the internet. HTTP (HyperText Transfer Protocol) is the most commonly used protocol for communication between Android apps and web services.
In this guide, we will go over how to use HTTP to interact with web services in Android. We will cover the following:
Web services are endpoints (URLs) that allow applications to send and receive data over the internet. These services typically provide data in formats like JSON or XML.
In this guide, we will focus on RESTful web services.
To consume web services in Android, you need to make HTTP requests to the web service’s endpoint. Android provides several ways to make these HTTP requests. The most common methods include using HttpURLConnection, HttpClient (deprecated), or third-party libraries like Retrofit or OkHttp.
For simplicity and ease of use, we will cover how to use HttpURLConnection (native Android approach) and Retrofit (third-party library) for making HTTP requests.
HttpURLConnection to Make HTTP RequestsHttpURLConnection is a standard Java class available in Android that you can use to send HTTP requests and receive responses.
A simple example of making a GET request to fetch data from a REST API:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String urlString = "https://jsonplaceholder.typicode.com/posts"; // API URL
String response = "";
try {
// Create URL object
URL url = new URL(urlString);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the HTTP method to GET
connection.setRequestMethod("GET");
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
response = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Handle the result (in this case, the JSON response)
}
}
Explanation:
HttpURLConnection: Opens an HTTP connection to the specified URL.setRequestMethod("GET"): Specifies that the HTTP method used will be GET.getInputStream(): Retrieves the data returned by the server.BufferedReader and stored as a string.Important: Networking operations like HTTP requests must be performed in a background thread to prevent blocking the main UI thread. In the example above, AsyncTask is used to run the request in the background.
A POST request is often used to send data to a server (e.g., for form submissions or creating new records). Here’s how to send data with a POST request:
import java.io.OutputStream;
public class NetworkTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String urlString = "https://jsonplaceholder.typicode.com/posts";
String response = "";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
// Enable input/output streams
connection.setDoOutput(true);
// Create the JSON data to send
String jsonData = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
// Send the JSON data
OutputStream os = connection.getOutputStream();
os.write(jsonData.getBytes());
os.flush();
os.close();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
response = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Handle the response (e.g., display the data in UI)
}
}
Explanation:
setDoOutput(true): This enables the output stream for sending data in the request body.getOutputStream().Retrofit is a modern and powerful HTTP client for Android, which simplifies consuming RESTful APIs. It automatically handles HTTP requests and responses, and can parse the responses into Java objects.
First, add Retrofit to your project by including the necessary dependencies in your build.gradle file:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0' // Retrofit core
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // Gson converter (for JSON parsing)
}
Define a Retrofit interface to describe the HTTP operations:
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface ApiService {
@GET("posts")
Call<List<Post>> getPosts(); // Method to fetch posts from the API
@POST("posts")
Call<Post> createPost(@Body Post post); // Method to create a new post
}
In this example, the getPosts() method will make a GET request to fetch posts, and the createPost() method will make a POST request to send a new post.
Now, create a Retrofit instance and use it to make requests:
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NetworkService {
private static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
public void fetchPosts() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
// Asynchronous request to get posts
Call<List<Post>> call = apiService.getPosts();
call.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (response.isSuccessful()) {
// Handle the response (list of posts)
List<Post> posts = response.body();
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
// Handle failure (e.g., network error)
}
});
}
}
Explanation:
Retrofit.Builder(): Creates a Retrofit instance.addConverterFactory(GsonConverterFactory.create()): Tells Retrofit to use Gson to parse JSON responses.enqueue(): Makes the request asynchronously.Retrofit automatically converts the JSON response into a Post object, making it easier to work with the response data.
Whether using HttpURLConnection or Retrofit, handling the responses involves:
HttpURLConnection and Retrofit allow you to check for error codes and handle failures.Example of checking for errors in Retrofit:
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (response.isSuccessful()) {
List<Post> posts = response.body();
// Process the posts
} else {
// Handle error response (e.g., HTTP 404, 500)
}
}
AsyncTask, Retrofit, or Executors) to avoid blocking the UI thread.Consuming web services using HTTP in Android is an essential task for mobile apps that interact with external systems or databases. By using tools like HttpURLConnection and third-party libraries like Retrofit, you can easily send requests and handle responses in Android. Always follow best practices for asynchronous operations, error handling, and security to ensure smooth and secure communication between your app and web services.
Open this section to load past papers