Выполнение вызовов API с использованием библиотеки Volley в Android
Volley — это библиотека HTTP, которая используется для кэширования и выполнения сетевых запросов в приложениях Android. Это HTTP-библиотека, которая упрощает и, самое главное, ускоряет сетевое взаимодействие приложений Android. API означает интерфейс прикладного программирования. Это способ взаимодействия двух или более компьютерных программ друг с другом. Используя свои продукты или услуги, общайтесь с другими продуктами и услугами, не зная, как они реализованы.
Note: This Android article covered in both Java and Kotlin languages.
Поэтапная реализация:
Шаг 1. Создайте новый проект в Android Studio.
Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio». Код для этого был предоставлен как на Java, так и на языке программирования Kotlin для Android.
Шаг 2. Добавьте доступ к Интернету в свое приложение.
Перейдите в приложение > файл manifest.xml и добавьте разрешение на доступ в Интернет. Ниже приведен код файла манифеста.
XML
<?xml version="1.0" encoding="utf-8"?> package="com.example.gfgvolleyapicall"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.GFGvolleyApiCall"> <activity android:name=".MainActivity" android:exported="true" tools:ignore="WrongManifestParent"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <!-- adding internet permission --> <uses-permission android:name="android.permission.INTERNET"/> </manifest> |
Шаг 3. Добавьте зависимость Volley в файл build.gradle (Module: app).
Перейдите в приложение > Gradle Scripts > файл build.gradle (Module: app) и добавьте зависимость. Ниже приведен код файла build.gradle.
plugins {
id ‘com.android.application’
}android {
compileSdk 31defaultConfig {
applicationId “com.example.gfgvolleyapicall”
minSdk 21
targetSdk 31
versionCode 1
versionName “1.0”testInstrumentationRunner “androidx.test.runner.AndroidJUnitRunner”
}buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}dependencies {
implementation ‘androidx.appcompat:appcompat:1.4.2’
implementation ‘com.google.android.material:material:1.6.1’
implementation ‘androidx.constraintlayout:constraintlayout:2.1.4’
testImplementation ‘junit:junit:4.13.2’
androidTestImplementation ‘androidx.test.ext:junit:1.1.3’
androidTestImplementation ‘androidx.test.espresso:espresso-core:3.4.0’implementation ‘com.android.volley:volley:1.2.1’ // adding volley dependency
}
Шаг 4: Работа с файлом activity_main.xml
Перейдите к app > res > layout > activity_main.xml и добавьте приведенный ниже код в этот файл. Ниже приведен код файла activity_main.xml .
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" android:backgroundTint="@color/white" app:layout_constraintTop_toTopOf="parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textColor="@color/purple_700" android:textSize="20sp" android:textAlignment="center" android:text="welcome to geeks for geeks" /> </LinearLayout> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> |
Шаг 5: Работа с файлом MainActivity
Перейдите в файл MainActivity и обратитесь к следующему коду. Ниже приведен код файла MainActivity . Комментарии добавляются внутри кода, чтобы понять код более подробно.
Java
package com.example.gfgvolleyapicall; import static android.content.ContentValues.TAG; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.util.Log;import android.widget.Toast; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; public class MainActivity extends AppCompatActivity { private RequestQueue mRequestQueue; private StringRequest mStringRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getData(); } private void getData() { // RequestQueue initialized mRequestQueue = Volley.newRequestQueue(this); // String Request initialized mStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show();//display the response on screen } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.i(TAG, "Error :" + error.toString()); } }); mRequestQueue.add(mStringRequest); }} |
Kotlin
package com.example.gfgvolleyapicall; import static android.content.ContentValues.TAG; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.util.Log;import android.widget.Toast; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; class MainActivity : AppCompatActivity() { private var mRequestQueue: RequestQueue? = null private var mStringRequest: StringRequest? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) getData() } private fun getData() { // RequestQueue initialized mRequestQueue = Volley.newRequestQueue(this) // String Request initialized mStringRequest = StringRequest(Request.Method.GET, url, object : Listener<String?>() { // display the response on screen fun onResponse(response: String) { Toast.makeText(applicationContext, "Response :$response", Toast.LENGTH_LONG) .show() } }, object : ErrorListener() { fun onErrorResponse(error: VolleyError) { Log.i(ContentValues.TAG, "Error :" + error.toString()) } }) mRequestQueue.add(mStringRequest) }} |
Выход: