Как сделать HTTP-запрос с Android?
В любом приложении для Android пользователь может сделать очень мало без подключения к Интернету. Все современные приложения для Android взаимодействуют с ресурсами, доступными в Интернете, или с серверной частью, специфичной для приложения. В этой статье мы рассмотрим один из способов, с помощью которых мы можем получать и публиковать ресурсы в Интернете с помощью HTTP-запросов. Мы будем использовать библиотеку Volley для обработки HTTP-запросов.
Обзор приложения
Мы создадим простое приложение, в котором будем использовать ImageView для отображения изображений собак и кнопку для получения изображения другой собаки. Всякий раз, когда кнопка будет нажата, будет сделан новый HTTP-запрос для получения изображения собаки, и оно будет отображаться в ImageView.
Пошаговая реализация
Шаг 1. Создайте новый проект в Android Studio.
Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio». Код для этого был предоставлен как на Java, так и на языке программирования Kotlin для Android.
Шаг 2: Добавьте необходимые зависимости
Перейдите к Gradle Scripts > build.gradle(Module:app) и добавьте приведенную ниже зависимость в раздел зависимостей.
1. Зависимость от библиотеки Volley.
implementation "com.android.volley:volley:1.2.1"
2. Библиотека обработки изображений Glide для кэширования и загрузки изображений из URL-адреса изображения, полученного из HTTP-запроса.
implementation "com.github.bumptech.glide:glide:4.13.2"
Шаг 3. Добавление разрешений на использование Интернета в файл AndroidManifest.xml
Чтобы наше приложение могло совершать сетевые вызовы, нам нужно сообщить системе Android, что нашему приложению для работы требуется Интернет. Мы можем сделать это, добавив разрешение на использование Интернета в файле манифеста Android .
Перейдите к приложению > манифесты > AndroidManifest.xml и добавьте в файл приведенный ниже фрагмент кода.
<!-- permissions for INTERNET --> <uses-permission android:name="android.permission.INTERNET"/>
Шаг 4: Работа с файлами XML
Перейдите к app > res > layout > activity_main.xml и добавьте приведенный ниже код в этот файл. Ниже приведен код файла activity_main.xml .
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" 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> |
Шаг 5: Работа с файлом MainActivity
Перейдите в файл MainActivity и обратитесь к следующему коду. Ниже приведен код файла MainActivity. Комментарии добавляются внутри кода, чтобы понять код более подробно.
Kotlin
import android.os.Bundleimport android.util.Logimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport com.android.volley.Requestimport com.android.volley.toolbox.JsonObjectRequestimport com.android.volley.toolbox.Volleyimport 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 // 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 // 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); }} |