1. 程式人生 > >android 訪問web端與解析json,模擬用戶登錄

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

android用戶登錄 與解析json數據

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

字符串格式如下:

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

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

註意: 在AndroidManifest.xml裏給訪問網絡的權限

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

步驟如下:

1、先做好頁面布局

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

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

4、new 一個子線程,在子線程裏通過HttpURLConnection 去請求數據

5、根據連接返回的狀態碼判斷是否成功連接

6、成功連接的話,就獲取response的數據,返回inputstream流

7、將流轉為String類型,通過UI線程的消息循環機制,將該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/imageView"
        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()){



            }


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

             /** 
             * 點擊按鈕事件,在主線程中開啟一個子線程進行網絡請求 
             * (因為在4.0只有不支持主線程進行網絡請求,所以一般情況下,建議另開啟子線程進行網絡請求等耗時操作)。 
             */
        //請求網絡
        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方式獲取數據
                    conn.setConnectTimeout(5000);              //設置連接超時時間5秒

                    int code = conn.getResponseCode();         // 獲取response狀態,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();
                        /**
                         * 子線程發送消息到主線程,並將獲取的結果帶到主線程,讓主線程來更新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;
    }
}


本文出自 “YuanGuShi” 博客,請務必保留此出處http://cm0425.blog.51cto.com/10819451/1941109

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