How to Communicate With Web Server in Android?

In order to store the data filled by an android application user on the Web Server, you have to  follow the following steps:

  1. Declare Internet permissions in the manifest by adding the following line to AndroidManifest.xml.
     <uses-permission android:name="android.permission.INTERNET"/>
  2. Create your HttpClient and HttpPost objects to execute the POST request.HttpClient myClient = new DefaultHttpClient();
     HttpPost post = new HttpPost("http://192.168.43.165/login.php");
  3. Remember not to use localhost while giving IP address of server file. As it will act as localhost of your phone rather that server, and will not allow you to do whatever you want.
  4. Set your POST data. This is done by creating and setting a list of NameValuePairs as your Http-Post’s entity. Be sure to catch the UnsupportedEncodingException thrown by HttpPost.setEntity().Execute the POST request. This returns an HttpResponse object, whose data can be extracted and parsed. Be sure to catch the ClientProtocolException and IOException thrown.
List<NameValuePair> myArgs = new ArrayList<NameValuePair>();
 myArgs.add(new BasicNameValuePair("username", "priyanka"));
 myArgs.add(new BasicNameValuePair("password", "pass"));
 post.setEntity(new UrlEncodedFormEntity(myArgs));
  1. Execute the POST request. This returns an HttpResponse object, whose data can be extracted and
    parsed. Be sure to catch the ClientProtocolException and IOException thrown.
 HttpResponse myResponse = myClient.execute(post);

Now process the response, the way you want.

Following is simple program on making HTTP connection. You can see output on Logcat.

package com.example.connect2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;


public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main_layout);
 
 }
 
 public void onConnect(View view) {
 new Thread(){
 public void run(){
 HttpClient myClient = new DefaultHttpClient();
 HttpPost post = new HttpPost("http://192.168.43.165/login.php");
 try {
 List<NameValuePair> myArgs = new ArrayList<NameValuePair>();
 myArgs.add(new BasicNameValuePair("username", "priyanka"));
 myArgs.add(new BasicNameValuePair("password", "pass"));
 post.setEntity(new UrlEncodedFormEntity(myArgs));
 HttpResponse myResponse = myClient.execute(post);
 BufferedReader br = new BufferedReader( new InputStreamReader(myResponse.getEntity().getContent()));
 String line = "";
 while ((line = br.readLine()) != null)
 {
 Log.d("mytag", line);
 
 }
 }
 catch (IOException e) {
 e.printStackTrace();
 }
 }
 }.start();
 
 }
}

main_layout.xml

<?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:orientation="vertical" >
 
 <Button android:id="@+id/connect"
 android:text="connect"
 android:onClick="onConnect"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>
 
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.connect2"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk
 android:minSdkVersion="15"
 android:targetSdkVersion="18" />
 
 <uses-permission android:name="android.permission.INTERNET"/>

 <application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="com.example.connect2.MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>

</manifest>

On pressing connect button, you can see this output on browser:

connectNote: Always create a new thread to do networking task. Otherwise your application would crash.

PHP file at backend is as follow:

<?php
 
/*
 * Following code authenticate the user.
 * 
 */
 
 if(isset($_POST['username']) && isset($_POST['password'])){
 $username = $_POST['username'];
 $password = $_POST['password'];
 
 require_once __DIR__ . '/db_connect.php';
 
 // connecting to database
 $db = new DB_CONNECT();
 
 //Array for JSON response
 $response = array();
 $response['success']=-1;
 $response['user_data']=array();

 $user_data = array();
 
 $login = "SELECT * FROM gcmuser WHERE user='$username' AND pass='$password';";
 $result = mysql_query($login);
 
 // Mysql_num_row is Counting table row
 $count = mysql_num_rows($result);
 // if it matches it counts to be one 1
 if($count==1)
 {
 session_start();
 $session = array();
 //On Success
 $response['success']=1;
 $session['valid_user']=$username;
 if($username=="admin"){
 $user_data['user']=$username;
 $user_data['user_type']=1;
 $session['user_type']=1;
 }
 else{
 $user_data['user']=$username;
 $user_data['user_type']=2;
 $session['user_type']=2;
 }
 array_push($response['user_data'],$user_data);
 echo json_encode($response);
 
 }
 else
 {
 // On Failure
 $response['success']=0;
 $response['user_data']=null;
 echo json_encode($response);
 
 }

 }
?>

db_connect.php

<?php
 
/**
 * A class file to connect to database
 */
class DB_CONNECT {
 
 // constructor
 function __construct() {
 // connecting to database
 $this->connect();
 }
 
 // destructor
 function __destruct() {
 // closing db connection
 $this->close();
 }
 
 /**
 * Function to connect with database
 */
 function connect() {
 // import database connection variables
 require_once __DIR__ . '/db_config.php';
 
 // Connecting to mysql database
 $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
 
 // Selecing database
 $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
 
 // returing connection cursor
 return $con;
 }
 
 /**
 * Function to close db connection
 */
 function close() {
 // closing db connection
 mysql_close();
 }
 
}
 
?>

db_config.php

<?php
 
/*
 * All database connection variables
 */
 
define('DB_USER', "root"); // db user
define('DB_PASSWORD', "priyanka"); // db password (mention your db password here)
define('DB_DATABASE', "enotice"); // database name
define('DB_SERVER', "localhost"); // db server
?>

MySQL table is gcmuser which has user and pass fields containing username and passwords.

connect2

Thats all. 🙂

Advertisements

About Priyanka Kapoor

Simple, Hardworking & friendly.....
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to How to Communicate With Web Server in Android?

  1. Abhimanyu Singh says:

    Madam .. Your posts are really very helpful . They are quite well explained and nicely formatted.
    Thank you. Keep it up 😀

  2. amatepm100 says:

    hi priyanka mam,
    thanks for this web server information.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s