ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP4124Consuming Web Services…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP4124

    Mobile Application Development 1

    Progress0 / 33 done
    Topics33
    1Mobiles Application Development Platform2HTML5 for Mobiles
    3Architecture, Framework and Application Development
    4Architecture, Framework5Application Development with Windows Mobile6Eclipse7Fragments8Calling Built-in Applications using Intents9Displaying Notifications10Components of a Screen11Adapting to Display Orientation12Managing Changes to Screen Orientation13Utilizing the Action Bar14Creating the User Interface15Listening for UI Notifications16Views17User Preferences18Persisting & Sharing Data19Sending SMS Messages20Getting Feedback21Sending E-mail22Displaying Maps23Consuming Web Services Using HTTP
    24Accessing and Creating25Threading26Publishing Android Applications27Deployment on App Stores28Mobile Programming Languages29Challenges with Mobility and Wireless Communication30Location-aware Applications31Performance/Power Tradeoffs32Mobile Platform Constraints33Emerging Technologies
    8 min read
    Topic 23 of 33
    Topic Study Note Illustration
    23

    Consuming Web Services Using HTTP

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

    Consuming Web Services Using HTTP in Android

    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:

    1. Understanding Web Services
    2. Making HTTP Requests in Android
    3. Handling Responses
    4. Best Practices for Consuming Web Services

    1. Understanding Web Services

    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.

    • RESTful Web Services: These services use HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources (such as data). They typically return data in JSON format.
    • SOAP Web Services: These services use XML-based messaging protocols to communicate, but they are less common in modern mobile development compared to REST.

    In this guide, we will focus on RESTful web services.


    2. Making HTTP Requests in Android

    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.


    A. Using HttpURLConnection to Make HTTP Requests

    HttpURLConnection is a standard Java class available in Android that you can use to send HTTP requests and receive responses.

    Making a GET Request with HttpURLConnection

    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.
    • The response is read using a 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.


    Making a POST Request with HttpURLConnection

    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.
    • The JSON data is written to the output stream using getOutputStream().
    • After sending the request, the server’s response is read from the input stream.

    B. Using Retrofit for HTTP Requests

    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.

    Adding Retrofit to Your Project

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

    Creating a Retrofit Interface

    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.

    Creating the Retrofit Instance

    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.


    3. Handling Responses

    Whether using HttpURLConnection or Retrofit, handling the responses involves:

    • Successful Response: When the server returns a valid response (HTTP 200), you can process the data, such as parsing the JSON.
    • Error Response: If the server returns an error (e.g., HTTP 404, 500), you need to handle the error gracefully. Both 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)
        }
    }
    

    4. Best Practices for Consuming Web Services

    • Async Operations: Always make network calls in a background thread (e.g., using AsyncTask, Retrofit, or Executors) to avoid blocking the UI thread.
    • Error Handling: Properly handle network errors, such as timeouts, server unavailability, or malformed responses.
    • JSON Parsing: Use a library like Gson or Moshi for parsing JSON responses to Java objects.
    • API Keys: If using a third-party API (e.g., Google Maps), ensure you store your API key securely (avoid hardcoding it directly in the code).
    • Security: Use HTTPS for secure communication between your app and web services.

    Conclusion

    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.

    ← Previous topic 22
    Displaying Maps
    Next topic 24 →
    Web Services: Accessing and Creating

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development 1