1. 程式人生 > >基於AndroidStudio開發Android實現簡單的註冊登入 POST方式提交資料

基於AndroidStudio開發Android實現簡單的註冊登入 POST方式提交資料

登入佈局頁面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.latitudeandlongitude.latitudeandlongitude.MainActivity">

    <EditText
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="78dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="使用者名稱" />

    <EditText
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/id"
        android:layout_below="@+id/id"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:inputType="textPassword"
        android:hint="密碼"/>

    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/password"
        android:layout_below="@id/password"
        android:text="記住使用者名稱和密碼"
        />
    <Button
        android:id="@+id/register"
        android:text="註冊"
        android:layout_marginTop="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_alignLeft="@+id/password"/>

    <Button
        android:id="@+id/login"
        android:text="登入"
        android:layout_marginTop="30dp"
        android:layout_below="@id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/password"/>

</LinearLayout>

註冊佈局頁面

<?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">

    <EditText
        android:id="@+id/id_edit"
        android:hint="使用者名稱"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/password_edit"
        android:hint="密碼"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/password_edit_1"
        android:hint="確認密碼"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/email_edit"
        android:hint="郵箱"
        android:layout_below="@+id/password_edit_1"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/register_do"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click1"
        android:text="註冊" />

</LinearLayout>

登入頁面邏輯

package com.example.latitudeandlongitude.latitudeandlongitude;

        import java.io.InputStream;
        import java.io.OutputStream;
        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.URL;

        import javax.security.auth.login.LoginException;

        import android.os.Bundle;
        import android.app.Activity;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.content.SharedPreferences.Editor;
        import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
        import android.text.TextUtils;
        import android.view.Menu;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.CheckBox;
        import android.widget.EditText;
        import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    private EditText id;
    private EditText password;
    private Button login;
    private Button register;
    public CheckBox cb;
    private String username;
    private String pwd;
    private SharedPreferences sp;
    private String result;
    private int RequestCode = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        id = (EditText) findViewById(R.id.id);
        password = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        //register.setOnClickListener(this);
        login.setOnClickListener(this);
        register = (Button) findViewById(R.id.register);

        register.setOnClickListener(this);
        cb = (CheckBox) findViewById(R.id.check);
        sp = getSharedPreferences("config", 0);
        //將資料顯示到UI控制元件
        //把config.xml檔案中的資料取出來顯示到EditText控制元件中
        //如果沒找到key鍵對應的值,會返回第二個預設的值
        String username = sp.getString("username", "");
        String password = sp.getString("password", "");
        id.setText(username);
        this.password.setText(password);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode==2){
            id.setText(data.getStringExtra("id"));
            password.setText(data.getStringExtra("password"));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                username = id.getText().toString().trim();
                pwd = password.getText().toString().trim();
                if(TextUtils.isEmpty(username)||TextUtils.isEmpty(pwd)){
                    Toast.makeText(this, "賬號或密碼不能為空",Toast.LENGTH_SHORT).show();
                }else{
                    new Thread(){


                        public void run(){
                            try {
                                //設定路徑
                                String path="http://192.168.1.111:8080/MyWebsite/androidlogin.do";
                                //建立URL物件
                                URL url=new URL(path);
                                //建立一個HttpURLConnection物件
                                HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                                //設定請求方法
                                conn.setRequestMethod("POST");
                                //設定請求超時時間
                                conn.setReadTimeout(5000);
                                conn.setConnectTimeout(5000);

                                //Post方式不能設定快取,需要手動設定
                                conn.setUseCaches(false);
                                //設定我們的請求資料
                                String data="id="+username+"&password="+pwd;
                                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//使用的是表單請求型別
                                conn.setRequestProperty("Content-Length", data.length()+"");
                                conn.setDoOutput(true);
                                conn.getOutputStream().write(data.getBytes());
//		                    //連線
//		                    conn.connect();
//							//獲取一個輸出流
//							OutputStream out=conn.getOutputStream();
//							out.write(data.getBytes());
                                //獲取伺服器返回的狀態嗎
                                int code=conn.getResponseCode();
                                if(code==200){
                                    //獲取伺服器返回的輸入流物件
                                    InputStream in= conn.getInputStream();
                                    result = StringTools.readStream(in);
                                    //更新UI
                                    runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            if(result.equals("success"))
                                                // TODO Auto-generated method stub
                                                Toast.makeText(getApplicationContext(), "登入成功", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent();
                                            intent.setClassName("com.example.latitudeandlongitude.latitudeandlongitude", "com.example.latitudeandlongitude.latitudeandlongitude.LocationActivity");
                                            startActivity(intent);
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        };
                    }.start();
                    if(cb.isChecked()){//判斷是否勾選
                        //使用sharePreferences區儲存資料 拿到sp例項
                        //引數:  name生成xml檔案
                        //mode 模式

                        //獲取sp的編輯器
                        Editor editor=sp.edit();
                        //儲存使用者輸入的資料
                        editor.putString("username", username);
                        editor.putString("password", pwd);
                        //提交editor
                        editor.commit();
                    }
                }
                break;
            case R.id.register:
                //跳轉到登入頁面
                Intent intent=new Intent(this,RegisterActivity.class);
                startActivityForResult(intent,RequestCode);
                break;
            default:
                break;
        }

    }
}

註冊頁面邏輯

package com.example.latitudeandlongitude.latitudeandlongitude;

import android.app.Activity;
import android.view.View;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by zhangwenhiu on 2018/10/28.
 */

public class RegisterActivity extends Activity implements View.OnClickListener{
    private Button register;
    private EditText id;
    private EditText pwd_1;
    private EditText pwd_2;
    private EditText emails;
    private String result;
    private String username;
    private String pwd1;
    private String email;
    private String pwd2;
    private int ResultCode=2;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        register = (Button) findViewById(R.id.register_do);
        register.setOnClickListener(this);
        id = (EditText) findViewById(R.id.id_edit);
        pwd_1 = (EditText) findViewById(R.id.password_edit);
        pwd_2 = (EditText) findViewById(R.id.password_edit_1);
        emails = (EditText) findViewById(R.id.email_edit);
    }

    @Override
    public void onClick(final View v) {
        new Thread(){public void run() {

            switch (v.getId()) {
                case R.id.register_do:
                    username = id.getText().toString().trim();
                    email = emails.getText().toString().trim();
                    pwd1 = pwd_1.getText().toString().trim();
                    pwd2 = pwd_2.getText().toString().trim();

                    //System.out.println("email:"+email);

                    if(!pwd1.equals(pwd2)){
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "兩次輸入密碼不一致,請重新輸入!", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else {
                        try {
                            //設定路徑
                            String path="http://192.168.1.111:8080/MyWebsite/androidregister.do";
                            //?id="+username+"&password=" + pwd1+ "&email=" +email+"
                            //建立URL物件
                            URL url=new URL(path);
                            //建立一個HttpURLconnection物件
                            HttpURLConnection conn =(HttpURLConnection) url.openConnection();
                            //設定請求方法
                            conn.setRequestMethod("POST");
                            //設定請求超時時間
                            conn.setReadTimeout(5000);
                            //conn.setConnectTimeout(5000);
                            //Post方式不能設定快取,需要手動設定
                            //conn.setUseCaches(false);
                            //準備要傳送的資料
                            String data ="id="+URLEncoder.encode(username,"utf-8")+"&password="+URLEncoder.encode(pwd1,"utf-8")+"&email="+URLEncoder.encode(email,"utf-8");
                            //String data ="id="+ username +"&password="+ pwd1 +"&email="+ email+"";
                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//使用的是表單請求型別
                            conn.setRequestProperty("Content-Length", data.length()+"");
                            conn.setDoInput(true);
                            conn.setDoOutput(true);
                            //連線
                            // conn.connect();
                            //獲得返回的狀態碼
                            conn.getOutputStream().write(data.getBytes());
                            int code=conn.getResponseCode();
                            if(code==200){
                                //獲得一個檔案的輸入流
                                InputStream inputStream= conn.getInputStream();
                                result = StringTools.readStream(inputStream);
                                //更新UI
                                showToast(result);
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    break;
            }


        };}.start();
    }
    public void showToast(final String content){
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(result.equals("success")){
                    Toast.makeText(getApplicationContext(), "註冊成功", Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent();
                    intent.putExtra("id", username);
                    intent.putExtra("password", pwd1);
                    setResult(ResultCode, intent);
                    finish();
                }

            }
        });
    }

}

執行截圖