Android Login and Registration Tutorial with PHP & MySQL

Total Views : 3,447
Zoom In Zoom Out Read Later Print

A very useful post about android login and registration. You know that a registration and login screen is part of almost of the application and if we talk about android then we have to save the user data in our server.

In this android login and registration tutorial we will create a very simple application that will contain 3 screens. The User Registration Screen, User Login Screen and the User Profile Screen.

Step #1:

For the server side part we will be using PHP and MySQL with XAMPP (you can use wamp or lamp as well) server.

Creating Web Services

The first part of this tutorial covers creating web services for User Signup and Login.  Now you may be thinking that why we need to create web services?

We need some medium between server and the application so that our application can access the database residing in our web server. For this we use Web Services often called APIs, more specifically a RESTful API.

#1.1 Creating Database

  • So first you create a new database in your PhpMyAdmin (localhost/phpmyadmin).
  • Inside the database we create the above shown table. And for this you can use the following query.

CREATE TABLE users (
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(200) NOT NULL,
email varchar(200) NOT NULL,
password text NOT NULL,
);
  • When you will execute the above given query in your database you will get the following table.
  • Now we have our database table where we will store the user data. Now lets create a PHP Project for our Web Services.

#1.2

  • Go to the htdocs folder, and create a new folder there. (This folder is actually our project). You can use any IDE like PHP Storm to create a new project but remember create it inside htdocs only .
  • Now the first step is the database connection.

Connection.php

<?php
$host = "localhost"; //Host
$username = "root"; //User
$password = "manjeet"; //Passsword
$database = "api"; // Database Name

//creating a new connection object using mysqli
$conn = new mysqli($host, $username, $password, $database);

//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error.
if ($conn->connect_error) {
die("Database connection failed: " . $conn->connect_error);
}
?>

#1.3 Building Web Services

  • For the current application we need Web Services for two action, the first one is Registration and the second one is Login.
  • For this create a new php file named Api.php. Inside this file we will handle all the API calls.
  • So write the following code inside Api.php.

Api.php

<?php
require_once 'Connection.php';
$response = array();
if(isset($_GET['action'])) {
switch($_GET['action']){
case 'signup':
if(isValid(array('username','email','password'))) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = md5($_POST['password']);

$stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0) {
//if user is new creating an insert
$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
//if the user is successfully added to the database
if($stmt->execute()){
$stmt = $conn->prepare("SELECT id, username, email FROM users WHERE username = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($id, $username, $email);
$stmt->fetch();

$user = array(
'id'=>$id,
'username'=>$username,
'email'=>$email
);
//adding the user data in response
$response['error'] = false;
$response['message'] = 'User registered successfully.';
$response['user'] = $user;
} else {
$response['error'] = true;
$response['message'] = 'Unable to create user.';
}
} else {
$response['error'] = true;
$response['message'] = 'User already registered.';
}
$stmt->close();
} else {
$response['error'] = true;
$response['message'] = 'Incomplete data.';
}
break;
case 'login':
if(isValid(array('username', 'password'))){
//getting values
$username = $_POST['username'];
$password = md5($_POST['password']);

//creating the check query
$stmt = $conn->prepare("SELECT id, username, email FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss",$username, $password);
$stmt->execute();
$stmt->store_result();

//if the user exist with given credentials
if($stmt->num_rows > 0) {
$stmt->bind_result($id, $username, $email);
$stmt->fetch();
$user = array(
'id'=>$id,
'username'=>$username,
'email'=>$email
);
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $user;
}else{
//if the user not found
$response['error'] = true;
$response['message'] = 'Invalid username or password';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid data.';
}
break;
default;
$response['error'] = true;
$response['message'] = 'Invalid Action.';
break;
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid Request.';
}
function isValid($params){
foreach($params as $param) {
//if the paramter is not available or empty
if(isset($_POST[$param])) {
if(empty($_POST[$param])){
return false;
}
} else {
return false;
}
}
//return true if every param is available and not empty
return true;
}
echo json_encode($response);
?>


Step #2 : Android Login and Registration

Now here comes the android coding part. The first thing we will do on the android side is the register operation. So create a new Android Studio Project.

#2.1 Designing User Interface

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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Profile"
android:id="@+id/btn_profile"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="LogIn"
android:id="@+id/btn_login"
android:layout_below="@+id/btn_profile"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SignUp"
android:id="@+id/btn_sign_up"
android:layout_below="@+id/btn_login"
android:layout_marginTop="20dp"/>
</RelativeLayout>

activity_signup.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.prodevsblog.phplogin.SignUpActivity">


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:padding="10dp">


<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:hint="Username"
android:inputType="text" />

<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:hint="Email"
android:inputType="textEmailAddress" />

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword" />

<Button
android:id="@+id/btn_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Register" />

<TextView
android:id="@+id/textViewLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Already Registered?\nLogin Here"
android:textAlignment="center"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
</LinearLayout>

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />

</RelativeLayout>

activity_login.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.prodevsblog.phplogin.LoginActivity">


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:padding="10dp">


<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:hint="Username"
android:inputType="text" />

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword" />

<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Login" />

<TextView
android:id="@+id/textViewRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Dont' have an account?\nRegister Here"
android:textAlignment="center"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

</LinearLayout>

<ProgressBar
android:visibility="gone"
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>

activity_profile.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.prodevsblog.phplogin.ProfileActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Id"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/textViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="-1"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Username"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/textViewUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text=""
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Email"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/textViewEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text=""
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</TableRow>
</TableLayout>
<Button
android:id="@+id/buttonLogout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
android:layout_marginTop="20dp"/>
</LinearLayout>
</RelativeLayout>

#2.2 Coding

URLS.java

package com.prodevsblog.phplogin;

public class URLS {
private static final String URL_ROOT = "http://192.168.43.199/api.php?action=";
public static final String URL_REGISTER = URL_ROOT + "signup";
public static final String URL_LOGIN= URL_ROOT + "login";
}

User.java

package com.prodevsblog.phplogin;

public class User {
private String username, email;
private int id;
public User(int id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}

public int getId() {
return id;
}
}

MainActivity.java

package com.prodevsblog.phplogin;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
void init(){
Button profile = findViewById(R.id.btn_profile);
Button login = findViewById(R.id.btn_login);
Button sign_up = findViewById(R.id.btn_sign_up);
PrefManager prefManager = PrefManager.getInstance(MainActivity.this);
if(prefManager.isLoggedIn()) {
login.setVisibility(View.GONE);
sign_up.setVisibility(View.GONE);
profile.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,ProfileActivity.class));
}
});
} else {
profile.setVisibility(View.GONE);
login.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,LoginActivity.class));
}
});
sign_up.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SignUpActivity.class));
}
});
}
}
}

SignUpActivity.java

package com.prodevsblog.phplogin;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;

public class SignUpActivity extends AppCompatActivity {
EditText editTextUsername, editTextEmail, editTextPassword;

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

editTextUsername = findViewById(R.id.editTextUsername);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);

findViewById(R.id.btn_register).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
registerUser();
}
});

findViewById(R.id.textViewLogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
}
});

}

private void registerUser() {
final String username = editTextUsername.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();

//validations
if (TextUtils.isEmpty(username)) {
editTextUsername.setError("Please enter username");
editTextUsername.requestFocus();
return;
}
if (TextUtils.isEmpty(email)) {
editTextEmail.setError("Please enter your email");
editTextEmail.requestFocus();
return;
}

if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError("Enter a valid email");
editTextEmail.requestFocus();
return;
}

if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Enter a password");
editTextPassword.requestFocus();
return;
}

//if it passes all the validations
//executing the async task
RegisterUser ru = new RegisterUser(username,email,password);
ru.execute();
}
private class RegisterUser extends AsyncTask<Void, Void, String> {
private ProgressBar progressBar;
private String username,email,password;
RegisterUser(String username,String email, String password){
this.username = username;
this.password = password;
this.email = email;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();

//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);

//returing the response
return requestHandler.sendPostRequest(URLS.URL_REGISTER, params);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("SignUp","sfdsds : "+s);
//hiding the progressbar after completion
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("username"),
userJson.getString("email")
);
//storing the user in shared preferences
PrefManager.getInstance(getApplicationContext()).setUserLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

LoginActivity.java

package com.prodevsblog.phplogin;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

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

import java.util.HashMap;

public class LoginActivity extends AppCompatActivity {

EditText editTextUsername, editTextPassword;

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

init();
}
void init(){
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
//if user presses on login calling the method login
findViewById(R.id.buttonLogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
userLogin();
}
});
//if user presses on not registered
findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//open register screen
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
});
}
private void userLogin() {
//first getting the values
final String username = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username)) {
editTextUsername.setError("Please enter username");
editTextUsername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Please enter password");
editTextPassword.requestFocus();
return;
}
//if everything is fine
UserLogin ul = new UserLogin(username,password);
ul.execute();
}
class UserLogin extends AsyncTask<Void, Void, String> {
ProgressBar progressBar;
String username, password;
UserLogin(String username,String password) {
this.username = username;
this.password = password;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(s);

//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");

//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("username"),
userJson.getString("email")
);

//storing the user in shared preferences
PrefManager.getInstance(getApplicationContext()).setUserLogin(user);

//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();

//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);

//returing the response
return requestHandler.sendPostRequest(URLS.URL_LOGIN, params);
}
}
}

ProfileActivity.java

package com.prodevsblog.phplogin;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class ProfileActivity extends AppCompatActivity {

TextView textViewId, textViewUsername, textViewEmail, textViewGender;

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

init();
}
void init(){
textViewId = findViewById(R.id.textViewId);
textViewUsername = findViewById(R.id.textViewUsername);
textViewEmail = findViewById(R.id.textViewEmail);

//getting the current user
User user = PrefManager.getInstance(this).getUser();

//setting the values to the textviews
textViewId.setText(String.valueOf(user.getId()));
textViewUsername.setText(user.getUsername());
textViewEmail.setText(user.getEmail());

//when the user presses logout button calling the logout method
findViewById(R.id.buttonLogout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
PrefManager.getInstance(getApplicationContext()).logout();
}
});
}
}

PrefManager.java

package com.prodevsblog.phplogin;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class PrefManager {
private static final String SHARED_PREF_NAME = "prodevsblogpref";
private static final String KEY_USERNAME = "user_name";
private static final String KEY_EMAIL = "user_email";
private static final String KEY_ID = "user_id";
private static final String KEY_IS_LOGGED_IN = "is_logged_in";
private static PrefManager mInstance;
private static Context mCtx;

private PrefManager (Context context) {
mCtx = context;
}

public static synchronized PrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new PrefManager(context);
}
return mInstance;
}
public void setUserLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getId());
editor.putString(KEY_USERNAME, user.getUsername());
editor.putString(KEY_EMAIL, user.getEmail());
editor.putBoolean(KEY_IS_LOGGED_IN,true);
editor.apply();
}
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
}

//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getInt(KEY_ID, -1),
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_EMAIL, null)
);
}
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}

RequestHandler.java

package com.prodevsblog.phplogin;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {

String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();

int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}


//method for converting key-value pairs data into a query string as needed to send to the server.
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}

See More

Latest Photos