How to send POST requests in JSON using HTTP Client in Android?


Introduction

Many android applications use APIs within their application so that they can interact with the database and perform read and write operations on the database. There are several libraries which we can use to make API calls within our android application. In this article we will take a look at How to send POST requests in JSON using HTTP Client in Android.

Implementation

We will be creating a simple application in which firstly we will be displaying the heading of our application. After that we will be creating two edit texts which are used to get the name and job. Then we will be creating a button which is used to post this data.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?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>

Explanation − In the above code the root element is a Relative layout in android. This layout is a view group which is used to align all the elements within it relative to each other. We can relatively align all elements within Relative Layout with the help of ids or positions.

Inside this relative layout we are creating a text view which is used to display the heading of our application. After that we are creating two edit texts in which users will be able to enter their name and job details. After that we are creating a button which is use to post the data to the API.

Step 3 : Adding internet permissions in AndroidManifest.xml file

As we are getting data from the internet using URLs we have to add internet permissions within our android application to access the internet to load this data. So we have to add internet permission. For adding internet permissions. Navigate to app>AndroidManifest.xml file and add below permission to it above the application tag.

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

Step 7 : Working with MainActivity.java.

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>java>your app’s package name>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

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;
      }
   }
}

Explanation − In the above code for the MainActivity.java file. Firstly we are creating a variable for our edit text and button Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file.

After specifying the view we are initializing our variables for edit text and button with its unique id which we have given in the activity_main.xml file.

After initializing our variables we are adding an on click listener for our button and inside the on click we are checking whether the edit text fields are empty or not. If they are empty then we are displaying the toast message. If they are not empty then we are creating a json object from them, converting that json object to the string and passing that json object to our PostData class.

PostData is an async task class inside which we are making an API call using HTTP Client to post the data to our API.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above tutorial we have taken a look at What is HTTP Client in Android and how we can use this HTTP client in android to post the data.

Updated on: 30-Mar-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements