Android Retrofit Post Request With Parameters JSON Example

android retrofit post request with parameters, android retrofit get request with parameters

Android Retrofit Post Request With Parameters JSON Example welcomes you.

You will learn to make http call using retrofit post request with parameters in this tutorial.

Several server calls like log in, registration, near by place etc. request need to have parameter with the URL.

For example, you want to fire login web service than you need to pass username and password along with the URL.

So here I will show you how to do this with retrofit POST request in android application.

Watch the Retrofit POST

Load the following video to see final outcome of this video.

 

PHP File

We are using the below php file ( simplelogin.php ) in this tutorial.

<?php

   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
       include_once("config.php");
       
        $username = $_POST['username'];
 	$password = $_POST['password'];
 	
	 if( $username == '' || $password == '' ){
	        echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
	 }else{
	 	$query= "SELECT * FROM registerDemo WHERE username='$username' AND password='$password'";
	        $result= mysqli_query($con, $query);
		 
	        if(mysqli_num_rows($result) > 0){  
	         $query= "SELECT * FROM registerDemo WHERE username='$username' AND password='$password'";
	                     $result= mysqli_query($con, $query);
		             $emparray = array();
	                     if(mysqli_num_rows($result) > 0){  
	                     while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
	                     }
	           echo json_encode(array( "status" => "true","message" => "Login successfully!", "data" => $emparray) );
	        }else{ 
	        	echo json_encode(array( "status" => "false","message" => "Invalid username or password!") );
	        }
	         mysqli_close($con);
	 }
	} else{
			echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
	}
?>

Step 1. Initial Works

Our first first task is to make a new project in android studio with empty activity.

After this, in the AndroidManifest.xml file, add the following line.

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

Above line is the internet permission. We need this permission to use the internet of the android device.

Now in your build.gradle(Module: app) file, write the following line

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
  • First line will fetch the classes of the retrofit 2 library.
  • Second will enable us to use the scalar library in our project.

Step 2. Retrofit Interface

For using retrofit, we need to make one Interface.

Make a new JAVA file and give it a name like PostInterface.java

Source code for PostInterface.java is looking like below file

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface PostInterface {

    String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";
    @FormUrlEncoded
    @POST("simplelogin.php")
    Call<String>  getUserLogin(
            @Field("username") String uname,
            @Field("password") String password
    );
}
  • first line is defining a string variable. This variable includes the URL for login.
  • Consider @POST(“simplelogin.php”). Here, @POST is saying that retrofit will make POST request.
  • Inside getUserLogin() method, there are two string parameters which we need to pass with the web service URL.

Step 3. Showing Credentials

Prepare a new activity called “Hobby Activity.”

System will create two files : activity_hobby.xml and HobbyActivity.java

Source code for activity_hobby.xml should look like the below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#edd712"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvusername"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:text="hello"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvpassword"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"/>


</LinearLayout>
  • This file includes two text views. One will hold the value of user name or first name.
  • Second text view will get the value of hobby in string format.

Now in HobbyActivity.java file, you should add the following source code

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class HobbyActivity extends AppCompatActivity {

    private TextView tvName, tvPass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hobby);

        tvName = findViewById(R.id.tvusername);
        tvPass = findViewById(R.id.tvpassword);

        tvName.setText(MainActivity.firstName);
        tvPass.setText(MainActivity.hobby);

    }
}
  • As we have added two text views in activity_hobby.xml , here we will get them using their ID.
  • Both these text views will get their values from two public string variables defined in the Main activity.

Step 4. Final and Main thoughts

Time to write two main files of this example : activity_main.xml and MainActivity.java

In your activity_main.xml file, add the below code snippet

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ec0d45"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="45sp"
        android:text="DemoNuts"
        android:textColor="#fff"
        android:layout_marginBottom="20dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etusername"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etpassword"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Login"
        android:textSize="29sp"
        android:background="#0bbc37"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"/>

</LinearLayout>
  • Above file have One text view, two edit texts and one button.
  • text view is just saying the company name.
  • I have added one edit text is for username and other one is for password.
  • When the user clicks the button, system will make the http call.

Now code structure for MainActivity.java is looking like the below

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private EditText etUname, etPass;
    private Button btn;
    public static String firstName, hobby;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etUname = findViewById(R.id.etusername);
        etPass = findViewById(R.id.etpassword);
        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

    }

    private void loginUser() {

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(PostInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        PostInterface api = retrofit.create(PostInterface.class);

        Call<String> call = api.getUserLogin(username,password);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        parseLoginData(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

    }

    public void parseLoginData(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,HobbyActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

Taking above code seriously

Let us see words of main activity in deep.

Consider the following code block

 private EditText etUname, etPass;
 private Button btn;
 public static String firstName, hobby;
  • First line is making an object of edit text and second one is of Button.
  • Third line making two public static string variables. We have used these variables in hobby activity.

Now read the below code block

  btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });
  • When the user clicks the button, compiler will execute the above code.
  • It will simply call the loginUser() method.

Following is the coding lines for  loginUser() method.

private void loginUser() {

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(PostInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        PostInterface api = retrofit.create(PostInterface.class);

        Call<String> call = api.getUserLogin(username,password);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        parseLoginData(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

    }
  • First two lines will declare the two string variables.
  • First one will get the string value from etUname edittext. It is the username entered by the user.
  • Second line will give the password of the user to the string variable from another edit text.
  • After this, compiler will create the object of the Retrofit class.
  • Here, .baseUrl(PostInterface.JSONURL) line is telling retrofit about the URL.
  • After this, compiler will create the object of the PostInterface and Call<String> classes.
  • Now, api.getUserLogin() method will get username and password as a parameter.
  • At this point, system have made the http call to the remote server. When the compiler get the response, it will call the onResponse() method.
  • Inside this onResponse() method, we will get the response in string format.
  • After this, compiler will call parseLoginData() method.

Following is the main source code for parseLoginData() method.

 public void parseLoginData(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,HobbyActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
  • First of all, compiler will check the value of “status” field of the JSON response. If this value is “true” then it will parse a json array.
  • Compiler will parse the Json array using the “data” field from the string json response.
  • Now it will go through one for loop. Inside for loop, it will get the value of “name” and “hobby.”
  • It will store these values into public string variables called “firstName” and “hobby.”

After this, system will open the Hobby Activity.

Download Source Code for Android Retrofit POST Request with Parameters

Click the below github link to download android studio source code.

https://github.com/demonuts/Android-Retrofit-POST-request-parameter-example