Android Login Screen Using HttpClient

Posted: 30/03/2013 in Android

 

I have updated this code to use web service and open new screen if the login is successful in my post Android Web Service Access Tutorial.

In Android we can use HTTP POST request with org.apache.http.client.HttpClient to post data to a URL. This sample project illustrate how we can post data to a URL and get the response. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.sencide;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
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.ClientProtocolException;
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;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class AndroidLogin extends Activity implements OnClickListener {
  
 Button ok,back,exit;
 TextView result;
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        // Login button clicked
        ok = (Button)findViewById(R.id.btn_login);
        ok.setOnClickListener(this);
         
        result = (TextView)findViewById(R.id.lbl_result);
         
    }
     
    public void postLoginData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
         
        /* login.php returns true if username and password is equal to saranga */
        HttpPost httppost = new HttpPost("http://www.sencide.com/blog/login.php");
 
        try {
            // Add user name and password
         EditText uname = (EditText)findViewById(R.id.txt_username);
         String username = uname.getText().toString();
 
         EditText pword = (EditText)findViewById(R.id.txt_password);
         String password = pword.getText().toString();
          
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 
            // Execute HTTP Post Request
            Log.w("SENCIDE", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);
             
            String str = inputStreamToString(response.getEntity().getContent()).toString();
            Log.w("SENCIDE", str);
             
            if(str.toString().equalsIgnoreCase("true"))
            {
             Log.w("SENCIDE", "TRUE");
             result.setText("Login successful");  
            }else
            {
             Log.w("SENCIDE", "FALSE");
             result.setText(str);            
            }
 
        } catch (ClientProtocolException e) {
         e.printStackTrace();
        } catch (IOException e) {
         e.printStackTrace();
        }
    }
   
    private StringBuilder inputStreamToString(InputStream is) {
     String line = "";
     StringBuilder total = new StringBuilder();
     // Wrap a BufferedReader around the InputStream
     BufferedReader rd = new BufferedReader(new InputStreamReader(is));
     // Read response until the end
     try {
      while ((line = rd.readLine()) != null) {
        total.append(line);
      }
     } catch (IOException e) {
      e.printStackTrace();
     }
     // Return full string
     return total;
    }
 
    @Override
    public void onClick(View view) {
      if(view == ok){
        postLoginData();
      }
    }
 
}

Following code is the content of mail.xml file that is used in the above code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:id="@+id/txt_username" android:layout_y="132dip" android:layout_x="128dip"></EditText>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:password="true" android:id="@+id/txt_password" android:layout_x="128dip" android:layout_y="192dip"></EditText>
<Button android:layout_width="100px" android:layout_height="wrap_content" android:id="@+id/btn_login" android:layout_x="178dip" android:layout_y="252dip" android:text="Login"></Button>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_username" android:text="User Name" android:layout_x="37dip" android:layout_y="150dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_password" android:text="Password" android:layout_y="207dip" android:layout_x="50dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_top" android:textSize="16sp" android:typeface="sans" android:text="Please Loggin First" android:layout_x="29dip" android:layout_y="94dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_y="312dip" android:layout_x="50dip" android:id="@+id/lbl_result"></TextView>
</AbsoluteLayout>

Following code is the content of AndroidManifest.xml file that is used in this project. There note that I have add the line <uses-permission android:name= “android.permission.INTERNET”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
      package="com.sencide"
      android:versionCode="1"
      android:versionName="1.0">
 
 <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidLogin"
                  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>
Advertisements

Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất / Thay đổi )

Connecting to %s