ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 1
    COMP4124
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    COMP4124›Web Services: Accessing and Creating
    Mobile Application Development 1Topic 24 of 33

    Web Services: Accessing and Creating

    7 minread
    1,212words
    Intermediatelevel

    Web Services: Accessing and Creating

    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.


    1. Accessing Web Services (Consuming Web Services)

    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:

    A. Understanding the HTTP Methods

    When interacting with RESTful web services, you typically use the following HTTP methods:

    • GET: Fetch data from the server.
    • POST: Send data to the server (e.g., create a new resource).
    • PUT: Update an existing resource on the server.
    • DELETE: Delete a resource on the server.

    B. Accessing Web Services Using HTTP in Android

    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.


    Using Retrofit to Access a Web Service

    1. Add Retrofit to your Android Project

    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.

    1. Define the Retrofit Interface

    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.

    1. Create the Retrofit Instance

    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.
    1. Define the Data Models

    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.

    1. Run the Application

    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.


    2. Creating Web Services (Developing Web Services)

    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).

    A. Setting Up a Spring Boot Application

    1. Create a Spring Boot Project

    Go to Spring Initializr and generate a new Spring Boot project with the following:

    • Project: Maven
    • Language: Java
    • Dependencies: Spring Web, Spring Boot DevTools
    1. Define a REST Controller

    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.
    1. Define the Data Model

    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
    }
    
    1. Run the Spring Boot Application

    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.

    1. Test the Web Service

    You can use a tool like Postman or cURL to test your web service.

    • GET Request: To fetch all posts:

      • URL: http://localhost:8080/posts
      • Method: GET
    • POST Request: To create a new post:

      • URL: http://localhost:8080/posts
      • Method: POST
      • Body (JSON format):
        {
            "title": "My first post",
            "body": "This is the content of the post."
        }
        

    3. Best Practices for Accessing and Creating Web Services

    • Data Validation: Always validate input data on both the client and server sides.
    • Error Handling: Provide proper error handling in both the client and server. For example, handle HTTP status codes such as 404 (Not Found) or 500 (Internal Server Error).
    • Security: Use secure communication (HTTPS) and consider adding authentication (e.g., OAuth, JWT) for sensitive operations.
    • Caching: Cache responses for frequently requested data to reduce server load and improve performance.
    • Rate Limiting: Protect your web services from being overloaded by implementing rate limiting, especially for publicly accessible APIs.

    Conclusion

    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.

    Previous topic 23
    Consuming Web Services Using HTTP
    Next topic 25
    Threading

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,212
      Code examples0
      DifficultyIntermediate