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


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.


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 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=""

   <!-- text view for displaying  heading of the application -->
      android:text="POST Request in Android using HTTP Client"
      android:textStyle="bold" />

   <!-- on below line creating edit text to enter name-->
      android:hint="Enter Name" />

   <!-- on below line creating edit text to enter job-->
      android:hint="Enter Job" />

   <!-- on below line we are creating a button to post the data -->
      android:text="Post Data"
      android:textAllCaps="false" />

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

Navigate to If this file is not visible. To open this file. In the left pane navigate to app>java>your app’s package name> 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.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 org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

   // on below line creating a variable for button and edit text.
   private Button postDataBtn;
   private EditText nameEdt, jobEdt;

   protected void onCreate(Bundle savedInstanceState) {
      // on below line we are initializing variables.
      postDataBtn = findViewById(;
      nameEdt = findViewById(;
      jobEdt = findViewById(;

      postDataBtn.setOnClickListener(new View.OnClickListener() {
         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) {


   // on below line creating a class to post the data.
   class PostData extends AsyncTask<String, Void, String> {

      protected String doInBackground(String... strings) {
      try {
            // on below line creating a url to post the data.
            URL url = new URL("");
            // on below line opening the connection.
            HttpURLConnection client = (HttpURLConnection) url.openConnection();
            // on below line setting method as 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.
            // 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) {
               // 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.
            Toast.makeText(MainActivity.this, "Fail to post the data : " + e.getMessage(), Toast.LENGTH_SHORT).show();
         return null;

Explanation − In the above code for the 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.



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

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started