How to Make an HTTP Request with Android?
Last Updated :
22 Jul, 2022
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.
implementation 'com.android.volley:volley:1.2.1'
2. Glide Image Processing Library for Caching and Loading Images from the Image URL Retrieved from the HTTP Request.
implementation 'com.github.bumptech.glide:glide:4.13.2'
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.
XML
<?xml version="1.0" encoding="utf-8"?>
<!-- Root layout of our activity -->
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- This ImageView is used to show the dog images to the user -->
<ImageView
android:id="@+id/dogImageView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/nextDogButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginHorizontal="6dp"
android:layout_marginBottom="10dp"
tools:srcCompat="@tools:sample/avatars" />
<!-- This Button is used for making a new HTTP request for fetching new dog image -->
<Button
android:id="@+id/nextDogButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Dog"
android:padding="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginBottom="30dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
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.
Kotlin
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.bumptech.glide.Glide
class MainActivity : AppCompatActivity() {
// member variable for holding the
// ImageView in which images will
// be loaded
private lateinit var mDogImageView: ImageView
private lateinit var nextDogButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// initialize the ImageView and the Button
mDogImageView = findViewById(R.id.dogImageView)
nextDogButton = findViewById(R.id.nextDogButton)
// attaching on click listener to the button so
// that `loadDogImage()` function is called
// everytime after clicking it.
nextDogButton.setOnClickListener { loadDogImage() }
// image of a dog will be loaded once
// at the start of the app
loadDogImage()
}
// function for making a HTTP request using
// Volley and inserting the image in the
// ImageView using Glide library.
private fun loadDogImage() {
// getting a new volley request
// queue for making new requests
val volleyQueue = Volley.newRequestQueue(this)
// url of the api through which we get random dog images
val url = "https://dog.ceo/api/breeds/image/random"
// since the response we get from the api is in JSON,
// we need to use `JsonObjectRequest` for
// parsing the request response
val jsonObjectRequest = JsonObjectRequest(
// we are using GET HTTP request method
Request.Method.GET,
// url we want to send the HTTP request to
url,
// this parameter is used to send a JSON object
// to the server, since this is not required in
// our case, we are keeping it `null`
null,
// lambda function for handling the case
// when the HTTP request succeeds
{ response ->
// get the image url from the JSON object
val dogImageUrl = response.get("message")
// load the image into the ImageView using Glide.
Glide.with(this).load(dogImageUrl).into(mDogImageView)
},
// lambda function for handling the
// case when the HTTP request fails
{ error ->
// make a Toast telling the user
// that something went wrong
Toast.makeText(this, "Some error occurred! Cannot fetch dog image", Toast.LENGTH_LONG).show()
// log the error message in the error stream
Log.e("MainActivity", "loadDogImage error: ${error.localizedMessage}")
}
)
// add the json request object created
// above to the Volley request queue
volleyQueue.add(jsonObjectRequest)
}
}
Java
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
// member variable for holding the ImageView
// in which images will be loaded
ImageView mDogImageView;
Button nextDogButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the ImageView and the Button
mDogImageView = findViewById(R.id.dogImageView);
nextDogButton = findViewById(R.id.nextDogButton);
// attaching on click listener to the button so that `loadDogImage()`
// function is called everytime after clicking it.
nextDogButton.setOnClickListener(View -> loadDogImage());
// image of a dog will be loaded once at the start of the app
loadDogImage();
}
// function for making a HTTP request using Volley and
// inserting the image in the ImageView using Glide library
private void loadDogImage() {
// getting a new volley request queue for making new requests
RequestQueue volleyQueue = Volley.newRequestQueue(MainActivity.this);
// url of the api through which we get random dog images
String url = "https://dog.ceo/api/breeds/image/random";
// since the response we get from the api is in JSON, we
// need to use `JsonObjectRequest` for parsing the
// request response
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
// we are using GET HTTP request method
Request.Method.GET,
// url we want to send the HTTP request to
url,
// this parameter is used to send a JSON object to the
// server, since this is not required in our case,
// we are keeping it `null`
null,
// lambda function for handling the case
// when the HTTP request succeeds
(Response.Listener<JSONObject>) response -> {
// get the image url from the JSON object
String dogImageUrl;
try {
dogImageUrl = response.getString("message");
// load the image into the ImageView using Glide.
Glide.with(MainActivity.this).load(dogImageUrl).into(mDogImageView);
} catch (JSONException e) {
e.printStackTrace();
}
},
// lambda function for handling the case
// when the HTTP request fails
(Response.ErrorListener) error -> {
// make a Toast telling the user
// that something went wrong
Toast.makeText(MainActivity.this, "Some error occurred! Cannot fetch dog image", Toast.LENGTH_LONG).show();
// log the error message in the error stream
Log.e("MainActivity", "loadDogImage error: ${error.localizedMessage}");
}
);
// add the json request object created above
// to the Volley request queue
volleyQueue.add(jsonObjectRequest);
}
}
Output:
Similar Reads
How to make an HTTP GET request manually with netcat?
Netcat,also known as "nc", is a powerful Unix-networking utility that enables users to interact with network services through a command-line interface (CLI). It uses both TCP and UDP network protocols for communication and is designed to be a reliable back-end tool to instantly provide network conne
6 min read
How to send a POST Request with PHP ?
In web development, sending POST requests is a common practice for interacting with servers and exchanging data. PHP, a versatile server-side scripting language, provides various approaches to accomplish this task. This article will explore different methods to send POST requests using PHP. Table of
3 min read
How to make HTTP requests in Node ?
In the world of REST API, making HTTP requests is the core functionality of modern technology. Many developers learn it when they land in a new environment. Various open-source libraries including NodeJS built-in HTTP and HTTPS modules can be used to make network requests from NodeJS.There are many
4 min read
Make HTTP requests in Angular?
In Angular, making HTTP requests involves communicating with a server to fetch or send data over the internet. It's like asking for information from a website or sending information to it. Angular provides a built-in module called HttpClientModule, which simplifies the process of making HTTP request
4 min read
How to Test API with REST Assured?
REST Assured is a Java library that provides a domain-specific language (DSL) for writing powerful, easy-to-maintain tests for RESTful APIs. It allows you to specify the expectations for HTTP responses from a RESTful API, and it integrates seamlessly with JUnit, the most popular testing framework fo
5 min read
How to Convert a Postman Request to cURL?
If you're a web developer, quality assurance engineer, or system administrator, chances are you're familiar with Postman, a crucial tool for API testing. However, there are instances where you may need to convert a Postman request to cURL, a command-line tool for data transfer. This article provides
3 min read
How Are Parameters Sent In An HTTP POST Request?
HTTP POST requests are widely used in web development to send data from a client to a server. Whether you're submitting a form, uploading a file, or sending JSON data via an API, understanding how parameters are sent in an HTTP POST request is important. In this article, weâll explore how are parame
4 min read
How to Create a Chatbot in Android with BrainShop API?
We have seen many apps and websites in which we will get to see a chatbot where we can chat along with the chatbot and can easily get solutions for our questions answered from the chatbot. In this article, we will take a look at building a chatbot in Android. What we are going to build in this artic
11 min read
How to Add Memes Using API Call in Android?
Application Programming Interface calling is the process of making requests to external web-based services to retrieve or manipulate data. APIs provide a standardized way for different software applications to communicate with each other. It involves sending a request from one application to another
4 min read
How to Send an HTTP POST Request in JS?
We are going to send an API HTTP POST request in JavaScript using fetch API. The FetchAPI is a built-in method that takes in one compulsory parameter: the endpoint (API URL). While the other parameters may not be necessary when making a GET request, they are very useful for the POST HTTP request. Th
2 min read