Login application in Android with HTTPS / Android app to communicate with the server using HTTPS



Before developing our application, just have a look at simple login application here, this will help you to understand the following example clearly.
Now lets make our server application to support HTTPS. Here I am using tomcat server v7.0 and a simple web application with a servlet.

1. Making Tomcat Ready:

To make our tomcat to use HTTPS, follow below steps;


Create a keystore file using 'keytool' of your JDK which will be located in the bin folder of your JDK.
In my machine it is in L:\Program Files\Java\jdk1.6.0_23\bin

Open command prompt type below command


keytool -genkey -alias tomcat -keyalg RSA


It will ask for keystore password. Give any password ( I gave password )

Re-enter the same password when prompted.

It will ask for first name and last name.

Give the host name of your application.(I gave 192.168.1.3)
For example my server application URL is https://192.168.1.3:8443/LoginApp/login.do
So the host name here is 192.168.1.3 . 

Note: I am going to use STRICT_HOSTNAME_VERIFIER in my android application which will check for the host name in the server certificate when connecting to a url. 

If you dont want this, then any name for the first and last name and use ALLOW_ALL_HOSTNAME_VERIFIER in your android app. 
You will get more idea when looking the android app code.

Give any values for other questions.


Finally the tool will ask you to enter the password for <tomcat> . 

Just press ENTER to use the same password which we gave in the first step.  
Note: <tomcat> is the alias name we gave in the command

Below is the screenshot of all these steps;



This will create a file called .keystore in your home directory. (In my macine it is L:\Users\Vienna)





We have created the keystore file and we need to use this in our tomcat. To do so, follow below steps


Goto your tomcat server installation path>conf folder. There you can see server.xml. Open this file in any editor. 



Search for the tag <Service name="Catalina">. Inside this tag you can see a tag <Connector port="8443".

Initially this will be inside comment block <!-- -->. 
Add below tag after the existing tag. ( I just want to keep the existing one untouched for future use)


<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 
               keystoreFile="${user.home}/.keystore" keystorePass="password"
/>

Here ${user.home} is a predefined variable which is pointing to your home directory. You can use absolute path also.

keystorePass is the password which we gave in the keytool.

Finally server.xml will look like;





We are done, restart your tomcat. 

You should see below message in the tomcat log. (Just for verification purpose)
INFO: Initializing ProtocolHandler ["http-nio-8443"]






2. Creating Server Application:

Now we need the server application to check the user name and the password. Here I have used a simple web application with a servlet. This application runs in a Tomcat server. You can have your own logic to validate the username and the password in the servlet. You can do database operations etc. But here I am just doing static validation of the username and password.




LoginServlet.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverside;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Vienna
 */
public class LoginServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP GET and POST methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
        String un,pw;
        un=request.getParameter("username");
        pw=request.getParameter("password");
        if(un.equalsIgnoreCase("hello") &amp;&amp; pw.equals("world"))
            out.print(1);
        else
            out.print(0);
        } finally {            
            out.close();
        }
    }

    // HttpServlet methods.
    /** 
     * Handles the HTTP GET method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP POST method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }//
}


We are ready with the server application. 
Now deploy your application in your tomcat and go to your browser and type https://192.168.1.3:8443/LoginApp/login.do

You should see below screen in your browser.
Note: I am using Internet Explorer


If you see this screen everything is ready with the server application.


3. Creating keystore.bks File:


We need openssl tool to make our android application use the server certificate and the Bouncy Castle Java cryptography APIs.
Download Bouncy Castle Java cryptography APIs from below url and extract the zip anywhere.

Download openssl tool from below link and extract the zip anywhere.

You can see the file openssl.exe inside the bin folder.

Now open command prompt. Go to this bin folder and type below command;

openssl s_client -connect 192.168.1.3:8443/LoginServer/>cert.pem

after seeing verify return:1 type exit and press ENTER



This command will create cert.pem inside the same folder. 


This file will contain the certificate key information. We need to make a small editing in this file. 
Open this cert.pem file in notepad, you can see something like

CONNECTED(00000070)
---
Certificate chain
 0 s:/C=Unknown/ST=Unknown/L=Unknown/O=Unknown/OU=Unknown/CN=192.168.1.3
   i:/C=Unknown/ST=Unknown/L=Unknown/O=Unknown/OU=Unknown/CN=192.168.1.3
---
Server certificate
-----BEGIN CERTIFICATE-----
MIICVzCCAcCgAwIBAgIEUO6RYjANBgkqhkiG9w0BAQUFADBwMRAwDgYDVQQGEwdV
bmtub3duMRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYD
VQQKEwdVbmtub3duMRAwDgYDVQQLEwdVbmtub3duMRQwEgYDVQQDEwsxOTIuMTY4
LjEuMzAeFw0xMzAxMTAxMDAxMDZaFw0xMzA0MTAxMDAxMDZaMHAxEDAOBgNVBAYT
B1Vua25vd24xEDAOBgNVBAgTB1Vua25vd24xEDAOBgNVBAcTB1Vua25vd24xEDAO
BgNVBAoTB1Vua25vd24xEDAOBgNVBAsTB1Vua25vd24xFDASBgNVBAMTCzE5Mi4x
NjguMS4zMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEYX+l5NQRFVK83Dyw
8Png099pr/JIKCutL0UgpgGI7nqmo9NJ2UQoLUF6DyogiHvR5kghOQRvID/FKLop
Ndj/RPUhEVvLkmo3SO4rJsEUfifC5BJWVFI0SU+PhdeMUfcrEyplJF3nzp9ckwUr
NgqTVkT+YsE3R0VW2JwjmWUtiQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAHOWnNsw
hxFPyqKBM/nEBq0hOGgCsaiMprve25rSpCtF5sOgZw0fGp7xe0y3DKdgyCBRtdDi
H3cXRV3et7eREPRc6w6wOp6PRoN3Bn/il7Xytx845Z5SZ2ADZlWhBBI7ohTMQrtp
M9jejbJFDO+oVjV/5pPm7cfIXhNSiL4lQIpY
-----END CERTIFICATE-----
subject=/C=Unknown/ST=Unknown/L=Unknown/O=Unknown/OU=Unknown/CN=192.168.1.3
issuer=/C=Unknown/ST=Unknown/L=Unknown/O=Unknown/OU=Unknown/CN=192.168.1.3
---
No client certificate CA names sent
---
SSL handshake has read 1183 bytes and written 290 bytes
---
New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA
Server public key is 1024 bit
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : DHE-RSA-AES256-SHA
    Session-ID: 50EE91DE7A499432BDB27D6F1C5E44AC3A56DB361A92787468140DA5F6DDE0F8
    Session-ID-ctx: 
    Master-Key: E6651E06205BCBA552C58E543787CDD935D6E1A8CCDBC528000478419BE08FF93AC19392A8AFBCE101654ADECBC57623
    Key-Arg   : None
    Start Time: 1357812190
    Timeout   : 300 (sec)
    Verify return code: 18 (self signed certificate)
---

Remove the contents above -----BEGIN CERTIFICATE----- and below -----END CERTIFICATE----- and save the file. So finally cert.pem file will contain;

-----BEGIN CERTIFICATE-----
MIICVzCCAcCgAwIBAgIEUO6RYjANBgkqhkiG9w0BAQUFADBwMRAwDgYDVQQGEwdV
bmtub3duMRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYD
VQQKEwdVbmtub3duMRAwDgYDVQQLEwdVbmtub3duMRQwEgYDVQQDEwsxOTIuMTY4
LjEuMzAeFw0xMzAxMTAxMDAxMDZaFw0xMzA0MTAxMDAxMDZaMHAxEDAOBgNVBAYT
B1Vua25vd24xEDAOBgNVBAgTB1Vua25vd24xEDAOBgNVBAcTB1Vua25vd24xEDAO
BgNVBAoTB1Vua25vd24xEDAOBgNVBAsTB1Vua25vd24xFDASBgNVBAMTCzE5Mi4x
NjguMS4zMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEYX+l5NQRFVK83Dyw
8Png099pr/JIKCutL0UgpgGI7nqmo9NJ2UQoLUF6DyogiHvR5kghOQRvID/FKLop
Ndj/RPUhEVvLkmo3SO4rJsEUfifC5BJWVFI0SU+PhdeMUfcrEyplJF3nzp9ckwUr
NgqTVkT+YsE3R0VW2JwjmWUtiQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAHOWnNsw
hxFPyqKBM/nEBq0hOGgCsaiMprve25rSpCtF5sOgZw0fGp7xe0y3DKdgyCBRtdDi
H3cXRV3et7eREPRc6w6wOp6PRoN3Bn/il7Xytx845Z5SZ2ADZlWhBBI7ohTMQrtp
M9jejbJFDO+oVjV/5pPm7cfIXhNSiL4lQIpY
-----END CERTIFICATE-----

Again go to bin folder of your JDK in command prompt and type below command;

keytool -import -alias tomcat -file L:/Users/Vienna/Desktop/cert.pem -keypass password -keystore L:/Users/Vienna/Desktop/keystore.bks -storetype BKS -storepass 222222 -providerClass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath L:/Users/Vienna/Desktop/bcprov-jdk15on-147.jar

Note: I copied my cert.pem fiel to my desktop and I have extracted the Bouncy castle api jar in my desktop. Please make a note of storepass that is 222222 in this case. We will be using this in our android application.


This command will ask Trust this certificate?[no]:

Type yes and press ENTER
This will create keystore.bks file in the desktop.
( I gave the path like L:/Users/Vienna/Desktop/keystore.bks )

Note: Android has inbuild support for BouncyCastle cryptography. So we use bks store here.





We are going to use this keystore.bks file in our android project.


We are now moving to final step-creating the android application.




4. Creating Android Application:


Create an android application in Eclipse name it as FirstApp.

Copy this keystore.bks file and paste it inside res/raw directory.

Note: If you do not have raw folder inside res, create it



Step 1: Create the layout for the application.

FirstApp/res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="510dip"
    android:layout_marginTop="10dip"
    android:background="#DDDDDD">
    <TextView
        android:id="@+id/tv_un"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="9dip"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="10dip"
        android:text="User Name:"/>
    <EditText
        android:id="@+id/et_un"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_un"
        android:layout_alignTop="@id/tv_un"
        android:inputType="text"
        />
     <TextView
        android:id="@+id/tv_pw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/tv_un"
        android:layout_marginRight="9dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="10dip"
        android:text="Password:"/>
    <EditText
        android:id="@+id/et_pw"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_pw"
        android:layout_alignTop="@id/tv_pw"
        android:layout_below="@id/et_un"
        android:inputType="textPassword"/>"
    <Button
        android:id="@+id/btn_login"
        android:layout_width="100dip"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_pw"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="160dip"
        android:text="Login" />
     <TextView
        android:id="@+id/tv_error"
        android:layout_width="400dip"
        android:layout_height="100dip"
        android:textSize="7pt"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/btn_login"
        android:layout_marginRight="9dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="120dip"
        android:textColor="#AA0000"
        android:text=""/>
</RelativeLayout>


Step 2: Create a java class to create UI threads.
com.example.firstapp.clientside.LoginLayout.java



/*
 * 
 */
package com.example.firstapp.clientside;

/**
 * @author Prabu
 *
 */
import java.util.concurrent.ExecutionException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.firstapp.R;

@SuppressLint("NewApi")
public class LoginLayout extends Activity {
 EditText un, pw;
 TextView finalResult;
 Button ok;
 private AsyncTask<String, String, String> asyncTask;
 private String response;
 private static Context context;

  /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  LoginLayout.context = getApplicationContext();
  setContentView(R.layout.activity_main);
  un = (EditText) findViewById(R.id.et_un);
  pw = (EditText) findViewById(R.id.et_pw);
  ok = (Button) findViewById(R.id.btn_login);
  finalResult = (TextView) findViewById(R.id.tv_error);
  ok.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    AsyncTaskRunner runner=new AsyncTaskRunner();
    String userName=un.getText().toString();
    String password=pw.getText().toString();
    asyncTask=runner.execute(userName,password);
    try {
     String asyncResultText=asyncTask.get();
     response = asyncResultText.trim();     
    } catch (InterruptedException e1) {
     response = e1.getMessage();
    } catch (ExecutionException e1) {
     response = e1.getMessage();
    } catch (Exception e1) {
     response = e1.getMessage();
    }
    finalResult.setText(response); 
   }
  });
 }
 
 public static Context getAppContext() {
        return LoginLayout.context;
    }
}


Step 3: Create a java class AsyncTaskRunner.java

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

To know more about AsyncTask go to below link
<link will be added soon>

com.example.firstapp.clientside.AsyncTaskRunner.java


/*
 * 
 */
package com.example.firstapp.clientside;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;

/**
 * @author Prabu
 *
 */
public class AsyncTaskRunner extends  AsyncTask<String,String,String>{

 private String resp;
 @Override
 protected String doInBackground(String... params) {
   int count = params.length;  
         if(count==2){
         ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
       postParameters.add(new BasicNameValuePair("username",params[0]));
       postParameters.add(new BasicNameValuePair("password",params[1]));
       String response = null;
   try {
    response = SimpleHttpClient.executeHttpPost("https://192.168.1.3:8443/LoginServer/login.do", postParameters);
    String res = response.toString();
    resp = res.replaceAll("\\s+", "");
   } catch (Exception e) {
    e.printStackTrace();
    resp = e.getMessage();
   }
         }else{
          resp="Invalid number of arguments-"+count;
         }
         return resp;
 }
}



Note: Use your server app url with https:// protocol. 




Step 4: Create a java class to post the username and password to a remote server

Normally the database and other resources like servlets will reside in separate computer and the Android application will communicate with that computer to authenticate the user. Thats why we are creating this java class.

com.example.firstapp.clientside.SimpleHttpClient.java




/*
 * 
 */
package com.example.firstapp.clientside;

/**
 * @author Prabu
 *
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.KeyStore;
import java.util.ArrayList;

import javax.net.ssl.HostnameVerifier;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import com.example.firstapp.R;

public class SimpleHttpClient {
 /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
         //sets up parameters
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "utf-8");
            params.setBooleanParameter("http.protocol.expect-continue", false);
            //registers schemes for both http and https
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", newSslSocketFactory(), 443));
            ClientConnectionManager manager = new ThreadSafeClientConnManager(params, registry);
            mHttpClient = new DefaultHttpClient(manager, params);
        }
        return mHttpClient;
    }
    
    private static SSLSocketFactory newSslSocketFactory() {
        try {
          KeyStore trusted = KeyStore.getInstance("BKS");
          InputStream in = LoginLayout.getAppContext().getResources().openRawResource(R.raw.keystore);
          try {
         // Keystore password comes in place of 222222
            trusted.load(in, "222222".toCharArray());
          } finally {
            in.close();
          }
          /*
           * If you use STRICT_HOSTNAME_VERIFIER, the the host name in the URL should match with
           * the host name in the server certificate. In this application it is 192.168.1.3
           * 
           * If you do not want to check the host name and simply want to connect to the URL, then use ALLOW_ALL_HOSTNAME_VERIFIER
           * 
           */
          //HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
          HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
          SSLSocketFactory socketFactory = new SSLSocketFactory(trusted);
          socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
          return socketFactory;
        } catch (Exception e) {
          throw new AssertionError(e);
        }
      }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Note: In the SimpleHttpClient java you can see the statement
trusted.load(in, "222222".toCharArray());
In this 222222 is the password we gave in previous step of creating keystore.bks file

keytool -import -alias tomcat -file L:/Users/Vienna/Desktop/cert.pem -keypass password -keystore L:/Users/Vienna/Desktop/keystore.bks -storetype BKS -storepass 222222 -providerClass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath L:/Users/Vienna/Desktop/bcprov-jdk15on-147.jar


Step 5: Add permissions to access internet



To be able to access the internet from the application (To send the user name and the password to the remote machine) we need to add permissions using following line to the AndroidManifest.xml file

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

So your final AndroidManifest.xml file will look like;




/*
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.firstapp"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="8"
        android:targetSdkVersion="16" />
 <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.firstapp.clientside.LoginLayout"
            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>


We are DONE now. Run your android application. 







If you see the correct response from the server we are done.

If you want to know the flow, add a breakpoint in your code and run the application in debug mode. 





Reactions:

11 comments :

  1. I always get incorrect username or password error.

    ReplyDelete
  2. Hi thanks for detail explanation. But when i try your code its returning this value in android

    The requested resource is not available. and some HTML tags.Please help with this problem

    ReplyDelete
    Replies
    1. Hi Piyush jain,
      Please post the error logs[or]those HTML tags.

      Delete
  3. HI Admin,
    I am using the 64 bit system and I have downloaded the 64 bit Openssl but the openssl is generating the below error.Do you have any idea.
    9744:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:.\ssl\s23_clnt.c:562:

    ReplyDelete
  4. HI,
    I am getting connection refused error on clicking the login button. What could be wrong ?

    ReplyDelete
  5. https://192.168.1.3:8443/LoginApp/login.do

    can i see that file??

    ReplyDelete
    Replies
    1. It is given on section 2.Creating Server Application

      Delete
  6. great tutorial, it works like a charm. many thanks

    ReplyDelete
  7. Great code I used with MS Soap WebService , thanks a lot!!

    ReplyDelete
  8. This works perfectly on the emulator, but gives a connection refused error on the actual device! what could be the problem? Thanks in advance

    ReplyDelete
    Replies
    1. In first case, both server and client are in same machine. So no problem. But in second case they are in different devices.To access the sever app from android mobile, your server app should be hosted on internet. One simple way is creating a web service and hosting it on internet.

      see this post to know to create a simple web service

      http://www.compiletimeerror.com/2013/09/creating-java-web-service-using-axis-2.html

      see this post to know how to access the web service from android application

      http://www.compiletimeerror.com/2013/09/accessing-web-service-from-android.html

      Delete

Ads