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
    EC-333
    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
    EC-333›Consuming Web Services Using HTTP
    Mobile Application DevelopmentTopic 23 of 33

    Consuming Web Services Using HTTP

    8 minread
    1,343words
    Intermediatelevel

    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 load past papers

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