溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android 訪問web端與解析json,模擬用戶登錄

發(fā)布時間:2020-06-23 08:54:46 來源:網(wǎng)絡 閱讀:915 作者:老婆的寶寶 欄目:移動開發(fā)

之前寫過一個java web端的登錄驗證,最后返回一個json字符串。

字符串格式如下:

{"appmsg":"賬號或密碼錯誤","appcode":0,"_default_boolean_a":false}

今天就結合著Android來寫一個簡單的登錄。

注意: 在AndroidManifest.xml里給訪問網(wǎng)絡的權限

            在寫具體路徑時,一定要注意不要用localhost,因為識別不了。一定要寫具體的IP

步驟如下:

1、先做好頁面布局

2、在activity中獲取用戶名、密碼

3、把用戶名、密碼附加到請求的地址上

4、new 一個子線程,在子線程里通過HttpURLConnection 去請求數(shù)據(jù)

5、根據(jù)連接返回的狀態(tài)碼判斷是否成功連接

6、成功連接的話,就獲取response的數(shù)據(jù),返回inputstream流

7、將流轉為String類型,通過UI線程的消息循環(huán)機制,將該String類型的結果返回到UI線程中

8、在UI線程中處理子線程中返回的結果

9、將String的結果轉為JSONObject對象,去獲取該對象中的code結果,0為登錄失敗,1為登錄成功。

10、彈出Toast,提示用戶登錄失敗或成功。


一、布局頁面

首先是一個頁面布局,如下

<?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"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <ImageView
        android:id="@+id/p_w_picpathView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_gravity="center_horizontal"
        app:srcCompat="@drawable/qq"/>

    <EditText
        android:id="@+id/et_qqNum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="請輸入QQ號碼"
        android:inputType="textPersonName"/>

    <EditText
        android:id="@+id/et_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="輸入密碼"
        android:inputType="textPassword"
        />

    <CheckBox
        android:id="@+id/cb_rember"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="記住密碼"
        />

    <Button
        android:id="@+id/bt_sub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="login"
        android:text="提交"/>

</LinearLayout>

2、MainActivity

package com.yuanlp.qqloginweb;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static final int LOAD_SUCCESS =1 ;
    private static final int LOAD_ERROR =2 ;
    private EditText mQqNum;
    private EditText mQqPwd;
    private CheckBox mCb_rember;
    /**
    *主線程中建一個handler,來獲取子線程中的Message
    *
    */
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case LOAD_SUCCESS:
                    boolean flag=checkLogin(msg.obj.toString());
                    if (flag){
                        Toast.makeText(MainActivity.this,"登錄成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this,"登錄失敗",Toast.LENGTH_SHORT).show();
                    }
                    sub.setEnabled(true);
            }
        }
    };


    private Button sub;
    private String mQq;
    private String mPwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       mQqNum= (EditText) findViewById(R.id.et_qqNum);
        mQqPwd = (EditText) findViewById(R.id.et_pwd);
        mCb_rember = (CheckBox) findViewById(R.id.cb_rember);
        sub = (Button) findViewById(R.id.bt_sub);

    }



    public void login(View view){
        //Toast.makeText(this,"點擊了提交",Toast.LENGTH_SHORT).show();
        mQq = mQqNum.getText().toString().trim();
        mPwd = mQqPwd.getText().toString().trim();
        //mCb_rember.getText().toString().trim();
        if (TextUtils.isEmpty(mQq)||TextUtils.isEmpty(mPwd)){
            Toast.makeText(this,"QQ號碼或者密碼為空",Toast.LENGTH_SHORT).show();
            return;
        }else {

            //選中了保存密碼
            if (mCb_rember.isChecked()){



            }


        }
        //這里設置按鈕不能點,應為一直點,就一直發(fā)送請求,會造成一直請求數(shù)據(jù)
        sub.setEnabled(false);

             /** 
             * 點擊按鈕事件,在主線程中開啟一個子線程進行網(wǎng)絡請求 
             * (因為在4.0只有不支持主線程進行網(wǎng)絡請求,所以一般情況下,建議另開啟子線程進行網(wǎng)絡請求等耗時操作)。 
             */
        //請求網(wǎng)絡
        new Thread(){
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    String path="http://192.168.1.111:10010/aos/pdaLogin.jhtml?username="+ mQq +"&password="+ mPwd;
                    URL url = new URL(path);
                    //打開httpurlconnection
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");              //設置get方式獲取數(shù)據(jù)
                    conn.setConnectTimeout(5000);              //設置連接超時時間5秒

                    int code = conn.getResponseCode();         // 獲取response狀態(tài),200表示成功獲取資源,404表示資源不存在
                    if (code==200){
                        InputStream is=conn.getInputStream();

                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        StringBuffer sb=new StringBuffer();
                        String len=null;

                        while((len=br.readLine())!=null){
                            sb.append(len);
                        }
                        String result=sb.toString();
                        /**
                         * 子線程發(fā)送消息到主線程,并將獲取的結果帶到主線程,讓主線程來更新UI。
                        */
                        Message msg= Message.obtain();
                        msg.what=LOAD_SUCCESS;
                        msg.obj=result;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg=Message.obtain();
                    msg.what=LOAD_ERROR;
                    handler.sendMessage(msg);
                }
            }
        }.start();

    }

    private boolean checkLogin(String result) {
        boolean flag=false;
        JSONObject jsonObject=null;
        try {
            jsonObject=new JSONObject(result);
            String code=jsonObject.get("appcode").toString();
            if ("0".equals(code)){
                flag=false;
            }else if("1".equals(code)){
                flag=true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return flag;
    }
}


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI