如何在Android中使用Volley傳送包含JSON資料的POST請求?


我們在Google Play商店上看到的許多Android應用程式都會進行API呼叫,以便從其資料庫中收集資料並在我們的應用程式中顯示這些資料。同樣,許多應用程式透過表單獲取使用者資料並將其儲存在其資料庫中。許多應用程式獲取使用者的地址等詳細資訊,以便將特定產品交付到他們的地址。為了釋出這些資料,有不同的方法,例如使用Volley、Retrofit等。在本文中,我們將瞭解如何在Android中使用Volley傳送包含JSON資料的POST請求。

實現

我們將建立一個簡單的應用程式,在這個應用程式中,我們將顯示兩個EditText欄位和一個按鈕。使用者必須在這些文字欄位中輸入姓名和職位,然後單擊按鈕提交這些資料。然後,我們將使用Android中的Volley透過發出POST請求將這些資料傳送到API。我們將使用一個示例API來進行此POST請求API呼叫,這將幫助我們釋出資料。釋出這些資料後,我們還將收到來自API的響應,這些響應將在我們的應用程式中顯示。

步驟1:在Android Studio中建立一個新專案

導航到Android Studio,如下圖所示。在下圖中,單擊“新建專案”以建立一個新的Android Studio專案。

單擊“新建專案”後,您將看到如下螢幕。

在此螢幕中,我們只需選擇“Empty Activity”並單擊“Next”。單擊“Next”後,您將看到如下螢幕。

在此螢幕中,我們只需指定專案名稱。然後包名將自動生成。

注意:確保選擇Java作為語言。

指定所有詳細資訊後,單擊“Finish”以建立一個新的Android Studio專案。

建立專案後,我們將看到開啟的兩個檔案,即activity_main.xml和MainActivity.java檔案。

步驟2:在build.gradle檔案中新增依賴項以使用此庫。

導航到Gradle Scripts>build.gradle檔案,並在dependencies部分新增以下依賴項。

implementation 'com.android.volley:volley:1.2.1'

在dependencies部分,我們將新增一個依賴項,該依賴項用於從API呼叫獲取資料以將其載入到我們的應用程式中。

新增上述依賴項後,您將在IDE的右上角看到“Sync Now”選項。只需單擊它即可同步您的專案並在您的專案中安裝此依賴項。

步驟3:使用activity_main.xml

導航到activity_main.xml。如果此檔案不可見,則要開啟此檔案。在左側窗格中,導航到app>res>layout>activity_main.xml以開啟此檔案。開啟此檔案後,向其中新增以下程式碼。程式碼中添加了註釋,以便詳細瞭解。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/idRLLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginStart="10dp"
       android:layout_marginTop="100dp"
       android:layout_marginEnd="10dp"
       android:gravity="center"
       android:text="POST Request using Volley"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp"
       android:textStyle="bold" />

   <!-- on below line creating edit text for name -->
   <EditText
       android:id="@+id/idEdtName"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="10dp"
       android:hint="Enter your Name"
       android:textAllCaps="false" />

   <!-- on below line creating edit text for name -->
   <EditText
       android:id="@+id/idEdtJob"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtName"
       android:layout_margin="10dp"
       android:hint="Enter your Job"
       android:textAllCaps="false" />

   <!-- progress bar for displaying a loading indicator -->
   <ProgressBar
       android:id="@+id/idPBLoading"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:indeterminate="true"
       android:indeterminateTint="@color/black"
       android:visibility="gone" />

   <!-- button for posting the data -->
   <Button
       android:id="@+id/idBtnPostData"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtJob"
       android:layout_margin="10dp"
       android:text="Post Data"
       android:textAllCaps="false" />

   <!-- tyext view for displaying the response -->
   <TextView
       android:id="@+id/idTVResponse"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idBtnPostData"
       android:layout_margin="10dp"
       android:gravity="center"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp"
       android:textStyle="bold" />
</RelativeLayout>

說明:在上面的程式碼中,根元素是Android中的相對佈局。在這個相對佈局中,我們正在建立一個簡單的TextView,我們將使用它來顯示應用程式的標題。之後,我們正在建立兩個EditText欄位,這些欄位將用於透過鍵盤從使用者那裡獲取我們必須釋出的資料。第一個EditText將用於獲取姓名,第二個EditText將用於從使用者那裡獲取職位。之後,我們顯示一個進度條,該進度條用作釋出資料時的載入指示器。在這個進度條之後,我們顯示一個按鈕,該按鈕用於釋出資料,單擊此按鈕時,我們將資料釋出到我們的伺服器。之後,我們將建立一個TextView,我們將在其中顯示來自我們API的響應。

步驟4:在AndroidManifest.xml檔案中新增網際網路許可權

由於我們正在從網際網路獲取資料,因此我們必須在我們的Android應用程式中新增網際網路許可權才能訪問網際網路以載入此資料。因此,我們必須新增網際網路許可權。要新增網際網路許可權,請導航到app>AndroidManifest.xml檔案,並在application標籤上方新增以下許可權。

<uses-permission android:name="android.permission.INTERNET"/>

步驟7:使用MainActivity.java

導航到MainActivity.java。如果此檔案不可見,則要開啟此檔案。在左側窗格中,導航到app>java>您的應用程式包名>MainActivity.java以開啟此檔案。開啟此檔案後,向其中新增以下程式碼。程式碼中添加了註釋,以便詳細瞭解。

package com.example.androidjavaapp;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
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;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
   // on below line we are creating variables
   private EditText nameEdt, jobEdt;
   private Button postDataBtn;
   private ProgressBar loadingPB;
   private TextView responseTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // on below line initializing variable with id.
       nameEdt = findViewById(R.id.idEdtName);
       jobEdt = findViewById(R.id.idEdtJob);
       postDataBtn = findViewById(R.id.idBtnPostData);
       loadingPB = findViewById(R.id.idPBLoading);
       responseTV = findViewById(R.id.idTVResponse);
       // on below line adding click listner for our post data button.
       postDataBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line checking of the edit text is empty or not.
               if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) {
                   Toast.makeText(MainActivity.this, "Pplease enter name and job..", Toast.LENGTH_SHORT).show();
               } else {
                   // on below line calling method to post the data.
                   postDataUsingVolley(nameEdt.getText().toString(), jobEdt.getText().toString());
               }
           }
       });
   }
   private void postDataUsingVolley(String name, String job) {
       // on below line specifying the url at which we have to make a post request
       String url = "https://reqres.in/api/users";
       // setting progress bar visibility on below line.
       loadingPB.setVisibility(View.VISIBLE);
       // creating a new variable for our request queue
       RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
       // making a string request on below line.
       StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
           @Override
           public void onResponse(String response) {
               // channing progress bar visibility on below line.
               loadingPB.setVisibility(View.GONE);
               // setting response to text view.
               responseTV.setText("Response from the API is :
" + response); // displaying toast message. Toast.makeText(MainActivity.this, "Data posted succesfully..", Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handling error on below line. loadingPB.setVisibility(View.GONE); responseTV.setText(error.getMessage()); Toast.makeText(MainActivity.this, "Fail to get response..", Toast.LENGTH_SHORT).show(); } }) { @Nullable @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our key // and value pair to our parameters. params.put("name", name); params.put("job", job); return params; } }; // adding request to queue to post the data. queue.add(request); } }

說明:在上面的MainActivity.java檔案的程式碼中。首先,我們為我們的TextView、按鈕、進度條和EditText建立變數。在onCreate方法中,我們使用我們在activity_main.xml檔案中給出的ID初始化我們的變數。初始化所有變數後,我們為我們的按鈕新增一個點選偵聽器。在點選偵聽器方法中,我們檢查EditText是否為空。如果EditText欄位為空,則我們將顯示一條吐司訊息,要求在EditText欄位中輸入資料。如果文字欄位不為空,則我們將呼叫postData方法來發布資料。

在使用Volley的postData方法中,我們傳遞name和job兩個變數。在此方法中,我們首先為必須在其上發出post請求的API的URL建立一個字串變數。之後,我們更改進度條的可見性。然後,我們初始化我們的RequestQueue變數並建立一個新的RequestQueue。然後,我們發出一個字串請求,在其中我們將請求型別指定為post請求,然後指定URL。現在,在response方法中,我們在我們的TextView中顯示響應。同樣,我們處理錯誤方法。我們在我們的TextView上顯示錯誤訊息。然後,我們呼叫getParams方法,在其中設定我們必須釋出到API的資料。在這裡,我們傳遞我們的name和job以釋出到API。最後,我們將此請求新增到佇列以釋出資料。

新增上述程式碼後,我們現在只需單擊頂欄中的綠色圖示即可在移動裝置上執行我們的應用程式。

注意:確保您已連線到您的真實裝置或模擬器。

輸出

結論

在上面的程式碼中,我們瞭解瞭如何在Android中使用JSON響應將資料釋出到API。同時,我們還了解了如何使用Volley庫釋出資料。

更新於:2023年5月9日

4K+ 瀏覽量

啟動您的職業生涯

完成課程後獲得認證

開始
廣告