Android 用戶端與伺服器端進行資料互動(二、登入用戶端)

來源:互聯網
上載者:User

標籤:

概要

Android用戶端分為User,HttpUtil,HttpCallbackListener,MainActivity四個部分。User model與服務端的一樣,一方面是用於本機使用者資訊的儲存model,另一方面也是為了保證構造URL時使用的key一致。
HttpUtil封裝了發送Http請求的過程和構造URL的函數,HttpCallbackListener是用於發送請求後的回調介面,MainActivity就是用於測試的Activity互動介面了。

User model

不再貼出,見上一篇 Android 用戶端與伺服器端進行資料互動(一、安卓用戶端)

HttpCallbackListener

回調介面定義了兩個函數,一個是正常結束時回調的onFinish,一個是出現異常時的onError

//請求回調介面public interface HttpCallbackListener {    void onFinish(String response);    void onError(Exception e);}
HttpUtil

HttpUtil是一個進行了二次封裝的Http工具類,包括了發送http請求的sendHttpRequest函數,組裝URL的getURLWithParams函數和網路狀態檢查函數。
組裝後的URL大概的樣子就像這樣”http://www.baidu.com?username=codingma&password=123456”

public class HttpUtil {    //封裝的發送請求函數    public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {        if (!HttpUtil.isNetworkAvailable()){            //這裡寫相應的網路設定處理            return;        }        new Thread(new Runnable() {            @Override            public void run() {                HttpURLConnection connection = null;                try{                    URL url = new URL(address);                    //使用HttpURLConnection                    connection = (HttpURLConnection) url.openConnection();                    //設定方法和參數                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(8000);                    connection.setReadTimeout(8000);                    connection.setDoInput(true);                    connection.setDoOutput(true);                    //擷取返回結果                    InputStream inputStream = connection.getInputStream();                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));                    StringBuilder response = new StringBuilder();                    String line;                    while ((line = reader.readLine()) != null){                        response.append(line);                    }                    //成功則回調onFinish                    if (listener != null){                        listener.onFinish(response.toString());                    }                } catch (Exception e) {                    e.printStackTrace();                    //出現異常則回調onError                    if (listener != null){                        listener.onError(e);                    }                }finally {                    if (connection != null){                        connection.disconnect();                    }                }            }        }).start();    }    //組裝出帶參數的完整URL    public static String getURLWithParams(String address,HashMap<String,String> params) throws UnsupportedEncodingException {        //設定編碼        final String encode = "UTF-8";        StringBuilder url = new StringBuilder(address);        url.append("?");        //將map中的key,value構造進入URL中        for(Map.Entry<String, String> entry:params.entrySet())        {            url.append(entry.getKey()).append("=");            url.append(URLEncoder.encode(entry.getValue(), encode));            url.append("&");        }        //刪掉最後一個&        url.deleteCharAt(url.length() - 1);        return url.toString();    }    //判斷當前網路是否可用    public static boolean isNetworkAvailable(){        //這裡檢查網路,後續再添加        return true;    }}
主活動

MainActivity就是最簡單的測試UI介面,包括了兩個輸入框和一個按鈕。
布局如下

布局xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              xmlns:tools="http://schemas.android.com/tools"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:gravity="center_horizontal|center_vertical"              android:orientation="vertical"              android:paddingBottom="@dimen/activity_vertical_margin"              android:paddingLeft="@dimen/activity_horizontal_margin"              android:paddingRight="@dimen/activity_horizontal_margin"              android:paddingTop="@dimen/activity_vertical_margin"              tools:context="com.pku.codingma.zhisms.ui.loginAndRegister.LoginActivityFragment"              tools:showIn="@layout/activity_main">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <TextView            android:layout_width="0dp"            android:layout_height="wrap_content"            android:text="手機號:"            android:inputType="phone"            android:layout_weight="1"/>        <EditText            android:id="@+id/phoneNumberEditText"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="5"/>    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <TextView            android:layout_width="0dp"            android:layout_height="wrap_content"            android:text="密碼:"            android:layout_weight="1"/>        <EditText            android:id="@+id/passwordEditText"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:inputType="textPassword"            android:layout_weight="5"/>    </LinearLayout>    <Button        android:id="@+id/loginButton"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="12dp"        android:background="@color/colorPrimaryDark"        android:text="login"/></LinearLayout>
MainActivity

MainActivity首先將輸入框中的使用者名稱和密碼取出,構造HashMap。再將其傳入HttpUtil.getURLWithParams函數中,構造出完整的URL,然後使用HttpUtil.sendHttpRequest發送請求,同時定義好回調介面要做的事情(即發出一條Message訊息)。最後通過Handler和Message訊息機制,根據請求返回結果做出對應的處理。

public class MainActivity extends AppCompatActivity implements View.OnClickListener{    private EditText mPhoneNumberEditText;    private EditText mPassWordEditText;    private Button mLoginButton;    //用於接收Http請求的servlet的URL地址,請自己定義    private String originAddress = "http://localhost:8080/Server/servlet/LoginServlet";    //用於處理訊息的Handler    Handler mHandler = new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            String result = "";            if ("OK".equals(msg.obj.toString())){                result = "success";            }else if ("Wrong".equals(msg.obj.toString())){                result = "fail";            }else {                result = msg.obj.toString();            }            Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        initEvent();    }    private void initView() {        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        mPhoneNumberEditText = (EditText) findViewById(R.id.phoneNumberEditText);        mPassWordEditText = (EditText) findViewById(R.id.passwordEditText);        mLoginButton = (Button) findViewById(R.id.loginButton);    }    private void initEvent() {        mLoginButton.setOnClickListener(this);    }    public void login() {        //檢查使用者輸入的帳號和密碼的合法性        if (!isInputValid()){            return;        }        //構造HashMap        HashMap<String, String> params = new HashMap<String, String>();        params.put(User.PHONENUMBER, mPhoneNumberEditText.getText().toString());        params.put(User.PASSWORD, mPassWordEditText.getText().toString());        try {            //構造完整URL            String compeletedURL = HttpUtil.getURLWithParams(originAddress, params);            //發送請求            HttpUtil.sendHttpRequest(compeletedURL, new HttpCallbackListener() {                @Override                public void onFinish(String response) {                    Message message = new Message();                    message.obj = response;                    mHandler.sendMessage(message);                }                @Override                public void onError(Exception e) {                    Message message = new Message();                    message.obj = e.toString();                    mHandler.sendMessage(message);                }            });        } catch (Exception e) {            e.printStackTrace();        }    }    private boolean isInputValid() {        //檢查使用者輸入的合法性,這裡暫且預設使用者輸入合法        return true;    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.loginButton:                login();                break;        }    }}
總結

Android端的稍微複雜一些,涉及Http請求發送,回調介面,一些有效性檢查,Handler訊息機制等等。不過都是最基礎的使用層級,應該不難理解。

希望這篇文章對新手有所協助,同時我自己在寫的過程中也有了更深的體會。
轉載請註明出處http://blog.csdn.net/u012145166/article/details/51334688
下載源碼,請猛戳這裡

Android 用戶端與伺服器端進行資料互動(二、登入用戶端)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.