In mobile application development, web services are commonly used to allow applications to communicate with external systems and retrieve or send data over the internet. Web services typically follow standards like REST (Representational State Transfer) or SOAP (Simple Object Access Protocol), with REST being the most popular for modern mobile applications due to its simplicity and scalability.
Here, we'll explain how to access (consume) and create web services, particularly focusing on RESTful web services, which are commonly used in mobile applications.
To access or consume a web service, your mobile application sends an HTTP request to a web service endpoint and processes the response.
Here are the main steps to access a web service:
When interacting with RESTful web services, you typically use the following HTTP methods:
In Android, you can use various libraries to send HTTP requests and process the responses, such as HttpURLConnection, Retrofit, or OkHttp. Below, we show an example of how to access a RESTful web service using Retrofit, which is the preferred choice due to its simplicity and ease of integration.
First, add Retrofit to your project by modifying the build.gradle file of your app:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0' // Retrofit core
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // Gson converter (for parsing JSON)
}
Sync your project after adding the dependencies.
Create an interface that describes the endpoints of the web service you want to interact with. Each method in the interface represents an API call.
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Body;
public interface ApiService {
// GET request to fetch data from a URL endpoint
@GET("posts")
Call<List<Post>> getPosts();
// POST request to send data to a URL endpoint
@POST("posts")
Call<Post> createPost(@Body Post post);
}
Here, the getPosts() method sends a GET request to fetch posts from the web service, while createPost() sends a POST request to create a new post.
In your Activity or ViewModel, create an instance of Retrofit to make API calls:
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()) {
List<Post> posts = response.body();
// Process the posts (e.g., display them in a RecyclerView)
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
// Handle failure (e.g., network error)
}
});
}
}
Explanation:
Retrofit.Builder(): Creates a Retrofit instance with the base URL and a converter to parse the response into Java objects.enqueue(): Makes an asynchronous request. The onResponse() method is called when the request succeeds, while onFailure() is called when there’s an error.GsonConverterFactory: Used to automatically parse the JSON response into Java objects using the Gson library.Data returned from the web service (e.g., posts) are often in JSON format. You’ll need to define model classes that correspond to the JSON structure.
public class Post {
private int id;
private String title;
private String body;
// Getters and setters
}
This model class represents a post object, where each field corresponds to a field in the JSON response.
Once everything is set up, you can run the fetchPosts() method to retrieve the data from the API. The response will be automatically parsed and ready for use in your application.
Creating your own web services involves setting up a server that can handle HTTP requests and return appropriate responses. A typical web service is built using a backend technology such as Node.js, Java (Spring Boot), Python (Flask/Django), or PHP.
For this example, we’ll focus on creating a simple RESTful web service using Spring Boot (a popular Java framework for building web applications).
Go to Spring Initializr and generate a new Spring Boot project with the following:
In your Spring Boot project, create a REST controller to handle incoming HTTP requests.
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/posts")
public class PostController {
// Simulating a database with a simple array
private List<Post> posts = new ArrayList<>();
// GET request to fetch all posts
@GetMapping
public List<Post> getPosts() {
return posts;
}
// POST request to create a new post
@PostMapping
public Post createPost(@RequestBody Post post) {
posts.add(post);
return post;
}
}
Explanation:
@RestController: Defines a REST API controller.@RequestMapping("/posts"): Maps the controller to the /posts URL path.@GetMapping: Maps HTTP GET requests to the getPosts() method to fetch posts.@PostMapping: Maps HTTP POST requests to the createPost() method to create new posts.Create a simple model class that represents the data structure for a post.
public class Post {
private String title;
private String body;
// Getters and setters
}
Run the Spring Boot application by executing the main() method in the Application class.
Once the application is running, you can access the web service via http://localhost:8080/posts.
You can use a tool like Postman or cURL to test your web service.
GET Request: To fetch all posts:
http://localhost:8080/postsGETPOST Request: To create a new post:
http://localhost:8080/postsPOST{
"title": "My first post",
"body": "This is the content of the post."
}
Accessing and creating web services is an essential part of mobile application development. Consuming web services allows your app to retrieve and send data over the internet, while creating web services enables you to expose your own functionality to be used by other applications. By following best practices and using the right tools (like Retrofit for consuming APIs and Spring Boot for creating APIs), you can easily integrate web services into your Android app.
Open this section to load past papers