How to Make an HTTP Request with Android?
In any Android Application, there is only so much a user can do without an internet connection. All modern Android Applications interact with resources available online or a backend-specific to the app. In this article, we will look at one of the ways through which we can retrieve and post resources online through HTTP Requests. We will use the Volley Library for handling HTTP requests.
Overview of the Application
We will be building a simple app in which we will use an ImageView for showing images of dogs and a button to get an image of another dog. Whenever the button will be pressed, a new HTTP request will be made for fetching a dog image and it will be displayed in the ImageView.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Add the Required Dependencies
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
1. Volley Library Dependency.
2. Glide Image Processing Library for Caching and Loading Images from the Image URL Retrieved from the HTTP Request.
Step 3: Adding Internet Usage Permissions to AndroidManifest.xml File
To enable our app to make network calls, we need to tell the android system that our app requires the internet to work. We can do this by adding internet usage permission in the Android Manifest File.
Navigate to app > manifests > AndroidManifest.xml and add the piece of code given below to the file.
<!-- permissions for INTERNET --> <uses-permission android:name="android.permission.INTERNET"/>
Step 4: Working with the XML Files
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 5: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.
Please Login to comment...