The Android client interacts with the server for data (two, login client)

Source: Internet
Author: User

Profile

The Android client is divided into four sections of user,httputil,httpcallbacklistener,mainactivity. The user model is the same as the server, on the one hand, the storage model for local user information, and the same key used to construct the URL.
Httputil encapsulates the process of sending HTTP requests and the function of constructing URLs, Httpcallbacklistener is the callback interface for sending requests, and mainactivity is the activity interaction interface for testing.

User model

No more post, see previous Android client interacts with server for data interaction (one, Android client)

Httpcallbacklistener

The callback interface defines two functions, one of which is the callback at the normal end of the onfinish, and the onerror when an exception occurs.

//请求回调接口publicinterface HttpCallbackListener {    void onFinish(String response);    void onError(Exception e);}
Httputil

Httputil is an HTTP tool class that has been encapsulated for two times, including the Sendhttprequest function that sends HTTP requests, the Geturlwithparams function for assembling URLs, and the network status check function.
The assembled URL looks like this, "http://www.baidu.com?username=codingma&password=123456."

 Public  class httputil {    //Package send request function     Public Static void sendhttprequest(FinalString address,FinalHttpcallbacklistener listener) {if(! Httputil.isnetworkavailable ()) {//write the corresponding network settings processing here            return; }NewThread (NewRunnable () {@Override             Public void Run() {HttpURLConnection connection =NULL;Try{URL url =NewURL (address);//Use HttpURLConnectionConnection = (httpurlconnection) url.openconnection ();//Setup methods and ParametersConnection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); Connection.setdoinput (true); Connection.setdooutput (true);//Get return resultsInputStream InputStream = Connection.getinputstream (); BufferedReader reader =NewBufferedReader (NewInputStreamReader (InputStream)); StringBuilder response =NewStringBuilder (); String Line; while(line = Reader.readline ())! =NULL) {response.append (line); }//Success Callback OnFinish                    if(Listener! =NULL) {Listener.onfinish (response.tostring ()); }                }Catch(Exception e) {E.printstacktrace ();//Unexpected exception callback OnError                    if(Listener! =NULL) {Listener.onerror (e); }                }finally{if(Connection! =NULL) {connection.disconnect ();    }}}). Start (); }//Assemble the full URL with parameters     Public StaticStringGeturlwithparams(String address,hashmap<string,string> params)throwsunsupportedencodingexception {//Set encoding        FinalString encode ="UTF-8"; StringBuilder URL =NewStringBuilder (address); Url.append ("?");//Key,value constructs in the map into the URL         for(Map.entry<string, String> entry:params.entrySet ()) {Url.append (Entry.getkey ()). Append ("=");            Url.append (Urlencoder.encode (Entry.getvalue (), encode)); Url.append ("&"); }//Erase Last &Url.deletecharat (Url.length ()-1);returnUrl.tostring (); }//Determine if the current network is available     Public Static Boolean isnetworkavailable(){//Check the network here and add it later        return true; }}
Main activity

Mainactivity is the simplest test UI interface, including two input boxes and a button.
The layout is as follows

Layout 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">    <linearlayoutandroid:layout_width="Match_parent"android:layout_height ="Wrap_content"android:orientation="Horizontal">                                <textview  android:layout _width  = "0DP"  android:layout_height  =< Span class= "Hljs-value" > "wrap_content"  android:text  =" mobile phone number: " android:inputtype  =" phone "
      android:layout_weight  = "1" />         <EditTextandroid:id="@+id/phonenumberedittext"android:layout_width= "0DP" android:layout_height="Wrap_content"android:layout_weight="5"/>                                                    </linearlayout>    <linearlayoutandroid:layout_width="Match_parent"android:layout_height ="Wrap_content"android:orientation="Horizontal">                                <TextViewandroid:layout_width="0DP"android:layout_height= "Wrap_content" Android:text="Password:"android:layout_weight="1"/>                                                        <EditTextandroid:id="@+id/passwordedittext"android:layout_width= "0DP" android:layout_height="Wrap_content"android:inputtype="Textpassword"  Android:layout_weight="5"/>                                                                </linearlayout>    <buttonandroid: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 first takes the username and password from the input box and constructs the HashMap. Then pass it into the Httputil.geturlwithparams function, construct the complete URL, then use Httputil.sendhttprequest to send the request, and define what the callback interface will do (that is, issue a message). Finally, the corresponding processing is made according to the request return result through the handler and message mechanism.

 Public  class mainactivity extends appcompatactivity implements View . Onclicklistener {    PrivateEditText Mphonenumberedittext;PrivateEditText Mpasswordedittext;PrivateButton Mloginbutton;//The URL address of the servlet used to receive the HTTP request, please define it yourself    PrivateString originaddress ="Http://localhost:8080/Server/servlet/LoginServlet";//handler for handling messagesHandler Mhandler =NewHandler () {@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() {//Check the legality of user-entered account and password        if(!isinputvalid ()) {return; }//Construction HashMaphashmap<string, string> params =NewHashmap<string, string> ();        Params.put (User.phonenumber, Mphonenumberedittext.gettext (). toString ()); Params.put (User.password, Mpasswordedittext.gettext (). toString ());Try{//Construct full URLString Compeletedurl = Httputil.geturlwithparams (originaddress, params);//Send requestHttputil.sendhttprequest (Compeletedurl,NewHttpcallbacklistener () {@Override                 Public void onfinish(String response) {Message message =NewMessage ();                    Message.obj = response;                Mhandler.sendmessage (message); }@Override                 Public void OnError(Exception e) {Message message =NewMessage ();                    Message.obj = E.tostring ();                Mhandler.sendmessage (message);        }            }); }Catch(Exception e)        {E.printstacktrace (); }    }Private Boolean Isinputvalid() {//Check the legality of user input, here is the default user input legal        return true; }@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.loginbutton:login (); Break; }    }}
Summarize

The android side is slightly more complicated, involving HTTP request sending, callback interface, some validity check, handler message mechanism and so on. However, they are the most basic level of use and should not be difficult to understand.

I hope this article will help the novice, while I myself in the process of writing also have a deeper experience.
Reprint please specify the source http://blog.csdn.net/u012145166/article/details/51334688
Download the source code, please poke here

The Android client interacts with the server for data (two, login client)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.