android端登陆功能实现

本文介绍了一个简单的Android登录界面实现方案,包括使用HttpClient提交用户名和密码到后台,以及基本的输入验证逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将用户名和密码通过httpClient提交到后台

登陆界面图如下:
这里写图片描述

Login.class

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.util.HttpUtils;
import com.util.Util;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import static android.widget.Toast.LENGTH_LONG;

/**
 * Created by virtualC9 on 2016/11/27.
 */

public class Login extends Activity{

    private TextView register;
    private TextView forgetPwd;
    private EditText emailEditText;
    private EditText passwordEditText;
    private Button regBtn;
    private Button loginBtn;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(R.layout.login);

        Intent intent=getIntent();
        String StringE=intent.getStringExtra("email");
        emailEditText=(EditText)findViewById(R.id.editEmail);
        emailEditText.setText(StringE);

        loginBtn = (Button) findViewById(R.id.btn_login);
        loginBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //emailEditText = (EditText) findViewById(R.id.editEmail);
                passwordEditText = (EditText) findViewById(R.id.editPassword);
                // TODO Auto-generated method stub
                String username = emailEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                String url = HttpUtils.LOGIN_URL;
                //执行输入校验
                if (validate(username, password)) {
                    //   load_dialog.show();//动画开始
                    //调用新线程
                    new _Thread(url, username, password).start();

                }
            }
        });
    }

    //启动新线程,数据传输需要在线程内完成
    public class _Thread extends Thread {
        String URL;
        String username;
        String password;
        String result;
        Message msg = new Message();
        Bundle bundle = new Bundle();

        public _Thread(String url, String username, String password) {
            this.URL = url;
            this.username = username;
            this.password = password;
        }

        @Override
        public void run() {
            super.run();

            msg.what = 0x11;
            bundle.clear();

            Log.i("message", "新线程启动");
            try {
                //发送参数
                Map<String, String> map = new HashMap<>();   //封装参数
                map.put("userForm.email", username);
                map.put("userForm.password", password);
                result = HttpUtils.Request(URL, map,"1");

                JSONObject json = new JSONObject(result);
                String state = json.get("state").toString();
                Log.i("result", "返回结果:" + state);

                if (state.equals("success")) {
                    //登陆成功
                    Util.savecookie(HttpUtils.cookie);  // 登陆成功后,保存cookie
                    //   Util.saveuserinfo(result);          // 保存用户信息

                    Log.i("message", "登陆成功");
                    bundle.putString("LoginSucc", "LoginSucc");
                    //登陆成功后跳转到主页
                    Login.this.startActivity(new Intent(Login.this, MainActivity.class));
                    Login.this.finish();
                }  if(state.equals("not_activation")){
                    //登录失败
                    Looper.prepare();
                    Toast.makeText(Login.this, "账号未激活,请到邮箱激活", LENGTH_LONG).show();
                    Looper.loop();
                    Log.i("message", "登陆失败");
                    bundle.putString("LoginFailed", "LoginFailed");
                } if(state.equals("error")){
                    //登录失败
                    Looper.prepare();
                    Toast.makeText(Login.this, "登陆失败", LENGTH_LONG).show();
                    Looper.loop();
                    Log.i("message", "登陆失败");
                    bundle.putString("LoginFailed", "LoginFailed");
                }

            } catch (Exception e) {

                Looper.prepare();
                Toast.makeText(Login.this, "检查网络连接", LENGTH_LONG).show();
                Looper.loop();
                Log.i("Exception", "JSONObj获取异常");

                bundle.putString("ServerException", "ServerException");

                e.printStackTrace();
            }
            msg.setData(bundle);
            // handler.sendMessage(msg);
        }
    }

    //判断用户是否是有效输入
    private boolean validate(String username, String password) {

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(getBaseContext(), "用户名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(getBaseContext(), "密码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    //还没账号,点击跳转到注册页面
    public void initRegister() {
        register = (TextView) findViewById(R.id.register);
        forgetPwd = (TextView) findViewById(R.id.lp_forgetPwd);
        regBtn = (Button) findViewById(R.id.btn_register);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(Login.this, Register.class);
                startActivity(intent);
            }
        });

        //忘记密码
        forgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(Login.this, ForgetPwd.class);
                startActivity(intent);
            }
        });
    }

}

HttpUtils.class

package com.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
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.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.DownloadManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

/**
 * Created by virtualC9 on 2016/12/16.
 */

public class HttpUtils {

    private static final String tag = "HttpUtils";

    // 创建HttpClient对象
    public static String cookie;
    public static String userinfo;
    //public static DefaultHttpClient httpClient = new DefaultHttpClient();

    // BASE_URL
    public static String IP="10.0.2.2";
    public static String LOGIN_URL = "http://"+IP+":8080/Passby/login.action"; // 登录地址
    public static String REGISTER_URL = "http://"+IP+":8080/Passby/register.action"; // 注册地址

    // Get连接服务器获取响应结果
    public static String GetRequest(final String url) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
        // HttpGet对象
        HttpGet get = new HttpGet(url);

        if(Util.getcookie()!=null){
            get.addHeader("cookie", Util.getcookie());
        }
        // HttpResponse对象
        HttpResponse httpResponse = httpClient.execute(get);
        // 获取服务器端响应
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream in = httpEntity.getContent();
                BufferedReader buff = new BufferedReader(new InputStreamReader(in));
                String results = "";
                String line = "";
                while ((line = buff.readLine()) != null) {
                    results = results + line;
                }
                System.out.println(results);
                Log.e("请求网络连接","成功");
                //Log.e(tag, "results:" + results);
                return results;
            }
        }
        return null;
    }
    public static Bitmap getImg(String address) throws IOException {
        URL url = new URL(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        try {
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
                return bitmap;
            } else {
                throw new IOException("Network Error - response code: " + conn.getResponseCode());
            }
        } finally {
            conn.disconnect();
        }
    }



    // post
    public static String PostRequest(String url, Map<String, String> rawParams) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // 创建HttpPost对象。
        HttpPost post = new HttpPost(url);
        //如果cookie存在,添加cookie
        if(Util.getcookie()!=null){
            post.addHeader("cookie", Util.getcookie());
        }
        // 如果传递参数个数比较多的话可以对传递的参数进行封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : rawParams.keySet()) {
            // 封装请求参数
            params.add(new BasicNameValuePair(key, rawParams.get(key)));
        }
        // 设置请求参数
        post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        // 发送POST请求
        HttpResponse httpResponse = httpClient.execute(post);
        // 如果服务器成功地返回响应
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            String result = EntityUtils.toString(httpResponse.getEntity());
            // System.out.println(result);
            return result;
        }
        return null;
    }

    /**
     * @Title: 登陆请求
     * @parm url 服务器路径
     * @parm rawParams 封装用户名和密码的map
     */
    public static String Request(String url, Map<String, String> rawParams,String code) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // 创建HttpPost对象。
        HttpPost post = new HttpPost(url);
        if(Util.getcookie()!=null){
            post.addHeader("cookie", Util.getcookie());
        }
        // 如果传递参数个数比较多的话可以对传递的参数进行封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : rawParams.keySet()) {
            // 封装请求参数
            params.add(new BasicNameValuePair(key, rawParams.get(key)));
        }
        // 设置请求参数
        post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        // 发送POST请求
        HttpResponse httpResponse = httpClient.execute(post);
        // 如果服务器成功地返回响应
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            Header[] heads = httpResponse.getAllHeaders();
            String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            JSONObject json = new JSONObject(result);
            String state = json.get("state").toString();
            //登陆成功后获取服务器返回的cookie保存到本地
            if (state.equals("success")&&code.equals("1")){
                cookie = Util.getusercookie(heads);
                Log.e(tag, "cookie:" + cookie);
            }
            return result;
        }
        return null;
    }

    /**
     * @Title: updateFile
     * @Description: 文件上传
     * @throws
     */
    public static String updateFile(String filePath,String url,String parameterName) throws UnsupportedEncodingException {
        //新建一个httpclient类
        HttpClient httpclient = new DefaultHttpClient();
        //用post方式实现文件上传
        HttpPost post = new HttpPost(url);
        if(Util.getcookie()!=null){
            post.addHeader("cookie", Util.getcookie());
        }
        ContentBody myFile = new FileBody(new File(filePath));

        MultipartEntity entity = new MultipartEntity();
        entity.addPart(parameterName, myFile);

        // 如果传递参数个数比较多的话可以对传递的参数进行封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
   /*     for (String key : upMap.keySet()) {
            // 封装请求参数
            params.add(new BasicNameValuePair(key, upMap.get(key)));
        }*/
        // 设置请求参数
        //post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        post.setEntity(entity);
        HttpResponse response = null;
        try {
            response = httpclient.execute(post);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result=null;
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            //拿到返回的实体,一般而言,用post请求方式返回的流是用这个实体拿到。
            HttpEntity entitys = response.getEntity();

            if (entity != null) {
                try {
                    result= EntityUtils.toString(entitys);
                    Log.e("图片上传状态",result);

                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        httpclient.getConnectionManager().shutdown();
        return result;
    }


    /**
     * @Title: updateFile
     * @Description: 文件上传
     * @throws
     */
    public static String upArticle(String filePath,String url,String parameterName,Map<String,String> upMap) throws UnsupportedEncodingException {
        //新建一个httpclient类
        HttpClient httpclient = new DefaultHttpClient();
        //用post方式实现文件上传
        HttpPost post = new HttpPost(url);
        if(Util.getcookie()!=null){
            post.addHeader("cookie", Util.getcookie());
        }
        ContentBody myFile = new FileBody(new File(filePath));

        MultipartEntity entity = new MultipartEntity();
        entity.addPart(parameterName, myFile);

        // 如果传递参数个数比较多的话可以对传递的参数进行封装

        if (upMap != null && !upMap.isEmpty()) {
            for (Map.Entry<String, String> entry : upMap.entrySet()) {
                StringBody contentBody = new StringBody(entry.getValue(),
                        "text/plain", Charset.forName("UTF-8"));
                entity.addPart(entry.getKey(), contentBody);
            }
        }
        post.setEntity(entity);
        HttpResponse response = null;
        try {
            response = httpclient.execute(post);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result=null;
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            //拿到返回的实体,一般而言,用post请求方式返回的流是用这个实体拿到。
            HttpEntity entitys = response.getEntity();

            if (entity != null) {
                try {
                    result= EntityUtils.toString(entitys);
                    Log.e("图片上传状态",result);

                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        httpclient.getConnectionManager().shutdown();
        return result;
    }


    /**
     * @Title: downLoadFile
     * @Description: 文件下载,app更新
     * @throws
     */

    public static String downLoadFile(String filePath,String fileName,String url,Context context){
        File file=new File(filePath);
        if (!file.exists()){
            file.mkdirs();
        }
        final DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //设置在什么网络情况下进行下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        //设置通知栏标题
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle("下载");
        request.setDescription("正在下载");
        request.setAllowedOverRoaming(false);
        //设置文件存放目录
        request.setDestinationInExternalPublicDir(filePath,fileName);
        // 获取此次下载的ID
        final long refernece = dManager.enqueue(request);
        // 把当前下载的ID保存起来
        SharedPreferences sPreferences = context.getSharedPreferences("downloadcomplete", 0);
        sPreferences.edit().putLong("refernece", refernece).commit();
        return null;
    }
}

login.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:background="@mipmap/login_bg"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:src="@mipmap/email_img"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/editEmail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@mipmap/email"
                android:ems="10"
                android:hint="请输入有效邮箱"
                android:textColorHint="@color/colorWhite"
                android:textCursorDrawable="@null"
                android:inputType="textEmailAddress"
                android:textColor="@color/colorWhite" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_marginTop="7dp"
            android:orientation="horizontal">

            <ImageView
                android:src="@mipmap/password_img"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/editPassword"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textCursorDrawable="@null"
                android:background="@mipmap/password"
                android:ems="10"
                android:hint="请输入密码"
                android:textColorHint="@color/colorWhite"
                android:inputType="textPassword"
                android:textColor="@color/colorWhite" />

        </LinearLayout>

        <Button
            android:id="@+id/btn_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:background="@mipmap/login_btn" />

    </LinearLayout>

    <TextView
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:gravity="bottom"
        android:text="@string/register"
    android:textColor="@color/colorWhite" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp">

        <TextView
            android:id="@+id/lp_forgetPwd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="@string/forgetPwd"
            android:textColor="@drawable/tv_btn_color" />
    </LinearLayout>
</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值