如何在Android中使用HTTP Client傳送JSON格式的POST請求?
簡介
許多Android應用程式在其內部使用API與資料庫互動,並對資料庫執行讀寫操作。我們可以使用多個庫在Android應用程式中進行API呼叫。本文將介紹如何在Android中使用HTTP Client傳送JSON格式的POST請求。
實現
我們將建立一個簡單的應用程式,首先顯示應用程式標題。然後,我們將建立兩個EditText用於獲取姓名和職位。接下來,我們將建立一個按鈕用於釋出這些資料。
步驟1:在Android Studio中建立一個新專案
導航到Android Studio,如下圖所示。在下圖中,單擊“新建專案”以建立一個新的Android Studio專案。

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

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

在這個螢幕中,我們只需指定專案名稱。然後包名將自動生成。
注意 – 確保選擇Java作為語言。
指定所有詳細資訊後,單擊“Finish”以建立一個新的Android Studio專案。
專案建立完成後,我們將看到兩個開啟的檔案:activity_main.xml和MainActivity.java檔案。
步驟2:使用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: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"> <!-- text view for displaying heading of the application --> <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:padding="5dp" android:text="POST Request in Android using HTTP Client" android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/black" android:textSize="18sp" android:textStyle="bold" /> <!-- on below line creating edit text to enter 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 Name" /> <!-- on below line creating edit text to enter job--> <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 Job" /> <!-- on below line we are creating a button to post 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="20dp" android:text="Post Data" android:textAllCaps="false" /> </RelativeLayout>
解釋 – 在上面的程式碼中,根元素是Android中的相對佈局。此佈局是一個檢視組,用於相對於彼此對齊其中的所有元素。我們可以藉助ID或位置在相對佈局中相對對齊所有元素。
在這個相對佈局中,我們建立了一個TextView用於顯示應用程式的標題。之後,我們建立了兩個EditText,使用者可以在其中輸入他們的姓名和職位詳細資訊。之後,我們建立了一個按鈕,用於將資料釋出到API。
步驟3:在AndroidManifest.xml檔案中新增Internet許可權
由於我們使用URL從Internet獲取資料,因此我們必須在Android應用程式中新增Internet許可權才能訪問Internet以載入此資料。因此,我們必須新增Internet許可權。要新增Internet許可權,請導航到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.content.Context; import android.media.AudioManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.toolbox.HttpClientStack; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { // on below line creating a variable for button and edit text. private Button postDataBtn; private EditText nameEdt, jobEdt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are initializing variables. postDataBtn = findViewById(R.id.idBtnPostData); nameEdt = findViewById(R.id.idEdtName); jobEdt = findViewById(R.id.idEdtJob); postDataBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) { Toast.makeText(MainActivity.this, "Please enter name and job", Toast.LENGTH_SHORT).show(); } else { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", nameEdt.getText().toString()); jsonObject.put("job", jobEdt.getText().toString()); String jsonString = jsonObject.toString(); new PostData().execute(jsonString); } catch (Exception e) { e.printStackTrace(); } } } }); } // on below line creating a class to post the data. class PostData extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... strings) { try { // on below line creating a url to post the data. URL url = new URL("https://reqres.in/api/users"); // on below line opening the connection. HttpURLConnection client = (HttpURLConnection) url.openConnection(); // on below line setting method as post. client.setRequestMethod("POST"); // on below line setting content type and accept type. client.setRequestProperty("Content-Type", "application/json"); client.setRequestProperty("Accept", "application/json"); // on below line setting client. client.setDoOutput(true); // on below line we are creating an output stream and posting the data. try (OutputStream os = client.getOutputStream()) { byte[] input = strings[0].getBytes("utf-8"); os.write(input, 0, input.length); } // on below line creating and initializing buffer reader. try (BufferedReader br = new BufferedReader( new InputStreamReader(client.getInputStream(), "utf-8"))) { // on below line creating a string builder. StringBuilder response = new StringBuilder(); // on below line creating a variable for response line. String responseLine = null; // on below line writing the response while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } // on below line displaying a toast message. Toast.makeText(MainActivity.this, "Data has been posted to the API.", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // on below line handling the exception. e.printStackTrace(); Toast.makeText(MainActivity.this, "Fail to post the data : " + e.getMessage(), Toast.LENGTH_SHORT).show(); } return null; } } }
解釋 – 在上面的MainActivity.java檔案的程式碼中,首先我們為EditText和按鈕建立一個變數。現在我們將看到onCreate方法。這是每個Android應用程式的預設方法。當建立應用程式檢視時,將呼叫此方法。在此方法中,我們將設定內容檢視,即名為activity_main.xml的佈局檔案,以設定該檔案中的UI。
指定檢視後,我們使用在activity_main.xml檔案中指定的唯一ID初始化EditText和按鈕的變數。
初始化變數後,我們為按鈕新增一個onClick監聽器,並在onClick中檢查EditText欄位是否為空。如果為空,則顯示吐司訊息。如果不為空,則從中建立一個JSON物件,將該JSON物件轉換為字串,並將該JSON物件傳遞給PostData類。
PostData是一個非同步任務類,我們使用HTTP Client在其中進行API呼叫以將資料釋出到我們的API。
新增上述程式碼後,我們只需單擊頂部欄中的綠色圖示即可在移動裝置上執行我們的應用程式。
注意 – 確保您已連線到您的真實裝置或模擬器。
輸出

結論
在上面的教程中,我們瞭解了Android中的HTTP Client是什麼,以及我們如何在Android中使用此HTTP Client來發布資料。