Android Client Implementation Registration, login details (2) _android

Source: Internet
Author: User
Tags constant gettext md5 object object stub throwable

The above describes the Android client and server interaction, the implementation of the registration function, Android client Registration/login details (i)

This article will continue to introduce the app and server interactive implementation of login and automatic login function, said the request server for registration is mainly through the post request to carry the parameter implementation, the main function of the code:

 Stringrequest request=new stringrequest (method.post, URL, new listener<string> () {

  //request successful
  @Override Public
  void Onresponse (String s) {
   //Execute request successful callback
   callback.onsuccess ()
  }

 }, new Errorlistener () {

  //Request error
  @Override public
  void Onerrorresponse (Volleyerror volleyerror) {
   //callback
   that failed to execute request Callback.onfailure ()
  }
 }) {

  //Carry Parameters (Map collection)
  @Override
  protected map<string, string> Getparams () throws Authfailureerror {return
   parames;
  }
 };

 Adds a request to the request queue
 Volley.newrequestqueue (context). Add (Request);

In fact, the principle of login implementation is the same, the same is through the post request, and in this demo is to request the server's method of encapsulation together, so the implementation of the login is also called Requestmanager Network request processing class in the Post method

/**
 * POST request Data
 *
 * @param app_url  Common interface prefix http://www.itlanbao.com/api/app/
 * @param tag_url  Interface name, EG:USERS/USER_REGISTER_HANDLER.ASHX (Registration Interface)
 * @param parameter request parameter Encapsulation object
 * @param clazz  Return Data encapsulation object, If NULL is passed, direct return string
 * @param callback Interface callback listener
/public static <T> void post (final string app_url, Final String Tag_url, final hashmap<string, string> parameter, class<t> clazz,
       final Httpresponecallback callback) {
 //Send POST request Server
 post (app_url, Tag_url, parameter, Clazz, callback, priority.normal);
}

Demo Demo

Implementation code

1. Data format of the server

1.url:http://www.itlanbao.com/api/app/users/user_login_handler.ashx

2. Parameter Description:
Email must have a mailbox
Password must have a password.
Accesstoken must have MD5 (email+password+ "both platforms agreed public key")

3. Request method: POST

4. Return value format
Success

 {
  "ret": 0,
  "Errcode": 0,
  "msg": "Login user interface Invoke Success",
  "data": {
   "userid": "16489",
   "email": " Nnn@aaa.com ",
   " nickname ":" Duss ",
   " Userhead ":" Http://img.itlanbao.com/avatar.png "
  }
  

Failed

 {
  "ret": 1,
  "Errcode": 1,
  "MSG": "Account or password error"
 }

2. Login interface (loginactivity), click the login button

 Click the login button
 Loginbtn.setonclicklistener (new Button.onclicklistener () {

  @Override public
  void OnClick ( View v {
   //TODO auto-generated method stub
   String accounts = Loginaccount.gettext (). toString ();//Account
   number String password = Loginpassword.gettext (). toString ();//Password
   if (! Textutils.isempty (account) &&! Textutils.isempty (password)
     && utils.isemail (account) {
    requestapidata.getinstance (). Getlogindata (account, password, userbaseinfo.class, loginactivity.this);
   } else {
    Toast.maketext (loginactivity.this, "Account or password incorrect", Toast.length_short). Show ();
 

The core code is:

 Incoming account names, passwords, bean objects and callbacks that parse the data (the incoming is itself, so loginactivity also implements the callback interface Httpresponecallback)
 Requestapidata.getinstance (). Getlogindata (account, password, userbaseinfo.class, loginactivity.this);

3. Network interface Class (Requestapidata)

 Create interface object public static Requestapidata getinstance () {if (instance = null) {instance = new Requestapidata ();
 return instance; /** * 4.8 Login User interface * @param email address * @param password password * @param clazz data returned resolution Object * @param callback callback * Special to Note that the parameter position cannot be changed according to the document * Request mode: POST/public void Getlogindata (string email, string password, class<userbaseinfo> c
   Lazz, Httpresponecallback callback) {mcallback = callback; This is the only indication of each interface String Tagurl = urlconstance.key_login_info;//Login Interface hashmap<string, string> parameter = new Hash
   Map<string, string> ();
   Parameter.put ("email", email);

   Parameter.put ("password", password);
   Splicing parameter information, mailboxes, passwords, public keys, and MD5 for encryption StringBuilder builder = new StringBuilder ();
   Builder.append (email);
   Builder.append (password);

   Builder.append (Urlconstance.public_key);

   Parameter.put (Urlconstance.accesstoken_key,md5util.getmd5str (builder.tostring ())); Request Data Interface Requestmanager.post (URLCONSTANCE.APP_Url,tagurl, parameter, Clazz, callback);

 }

4. Request the data in the Network Request processing Class (Requestmanager) , and register to execute the same method, just here the incoming tag_url for the login interface

 /** * POST Request data * * @param app_url Common interface prefix http://www.itlanbao.com/api/app/* @param tag_url interface name, Eg:users/use R_LOGIN_HANDLER.ASHX (Login interface) * @param parameter request parameter Encapsulation Object * @param clazz returns the data encapsulation object and returns a string * @param if NULL is passed CALLBAC K-Interface callback monitor/public static <T> void post (final string app_url, final string tag_url, final hashmap<string, Stri ng> parameter, class<t> clazz, Final Httpresponecallback callback) {//Send POST Request Server post (App_url, Tag_
 URLs, parameter, Clazz, callback, Priority.normal); /** * POST Request data * * @param app_url path * @param URL Interface name * @param parameter Request parameter Encapsulation Object * @param clazz return Data seal Load object, if NULL, returns String * @param callback Interface Callback Monitor * @param priority specifies interface request thread priority/public static <T> void post
        (Final string app_url, final string url, final hashmap<string, string> parameter, final class<t> Clazz, Final Httpresponecallback callback, Priority Priority) {if (callback!= null) {CallbaCk.onresponestart (URL);//callback Request Start} initrequestqueue (); Stitching the public interface prefix and interface name//eg: Stitching into the login interface Http://www.itlanbao.com/api/app/users/user_login_handler.ashx StringBuilder
  Builder = new StringBuilder (App_url);

  Builder.append (URL);

   {//Check if the current network is available final networkutils networkutils = new Networkutils (Itlanbaolibapplication.getinstance ());
     if (!networkutils.isnetworkconnected () && Android.os.Build.VERSION.SDK_INT >) {if (callback!= null) {
    Callback.onfailure (URL, null, 0, "network error");/callback request failed return; /** * Use the volley framework to actually request the server * Method.post: Request for POST * builder.tostring (): Requested link * listener<string : monitoring/Stringrequest request = new Stringrequest (Method.post, builder.tostring (), New listener<string> ( {@Override public void Onresponse (String response) {//TODO auto-generated Method Stub//This position first
        Common parse-handling joint exception try {if (response!= null && callback!= null) {Gson Gson = new Gson ();

       The callback request succeeds, while the URL and the parsed object callback.onsuccess (URL, Gson.fromjson (response, clazz));
        } catch (Exception e) {//Todo:handle Exception if (callback!= null) {//Callback request failed--parse exception
        Callback.onfailure (URL, E, 0, "parse exception");
       Return '}} ', new Errorlistener () {///Request error listening @Override public void Onerrorresponse (volleyerror error {if (callback!= null) {if (Error!= null) {callback.onfailure (URL, error.getcause (), 0, error
     . GetMessage ());
     else {callback.onfailure (URL, null, 0, ""); }}}) {//post requested parameter information protected map<string, string> Getparams () {return Getpostapiparmes (para
   meter);

  }
  };
 Add a request to the request queue addrequest (request, URL); 
 * * * Post parameter * TS: Timestamp sign: interface signature parms = parm[0]+ by document parameters ... + parm[n-1] Sign = * MD5 (parms+ "both platforms agreed public key") * * private static Apiparams Getpostapiparmes (final Hashmap<string, string> parameter) {Apiparams API = new Apiparams ();
  For (entry<string, string> entry:parameter.entrySet ()) {Api.with (Entry.getkey (), Entry.getvalue ());
 } return API;

 }

5. Also return to Loginactivity to execute callback , Failure prompts, success will save login information to SP neutralization application

@Override public void Onresponestart (String apiname) {//TODO auto-generated Method stub if (urlconstance.key_login_i
 Nfo.equals (Apiname)) {Toast.maketext (loginactivity.this, "Loading Data", Toast.length_short). Show (); @Override public void onloading (String apiname, Long count, long current) {//TODO auto-generated method stub} @O Verride public void onsuccess (String apiname, Object object) {//TODO auto-generated Method stub if (urlconstance.key_l Ogin_info.equals (Apiname)) {//Mailbox login return Data if (object!= null && object instanceof userbaseinfo) {Userbaseinf
   o info = (userbaseinfo) object; if (Info.getret (). Equals (constant.key_success)) {//login succeeded, save login Information Itlanbaoapplication.getinstance (). Setbaseuser (INF

    o);//Save in application//save to SP Userpreference.save (keyconstance.is_user_id, String.valueof (Info.getuserid ()));
    Userpreference.save (Keyconstance.is_user_account, Info.getemail ()); Userpreference.save (Keyconstance.is_user_password, LoginpasSword.gettext (). toString ());
    Intent Intent = new Intent ();
    Intent.setclass (Loginactivity.this, Mainactivity.class);
    StartActivity (Intent); Overridependingtransition (Android. R.anim.slide_in_left, Android.
    R.anim.slide_out_right);

   Finish ();
    else {log.e ("TAG", "info=" +info.tostring ()); if (Info.geterrcode (). Equals (Constant.key_no_regist)) {Toast.maketext (Loginactivity.this, "Logon Failed", Toast.length_
    Short). Show ();
     else {toast.maketext (loginactivity.this, Info.getmsg (), Toast.length_short). Show ();
    LOG.E ("TAG", "info.getmsg () =" +info.getmsg ()); @Override public void OnFailure (string apiname, Throwable t, int errorno, string strMsg) {/To 
Do auto-generated method Stub toast.maketext (loginactivity.this, "failure", Toast.length_short). Show ();

 }

6. Automatic Login Implementation , in fact, we are in the Welcome page to make a judgment: Read the information in the SP, if there is login information, then take out, carry this Information request server (with login request), if successful, Jump directly to the main page, or if the login is unsuccessful or if there are no saved login information in the SP, jump to the login interface, as follows (welcomeactivity)

   String useraccount = Userpreference.read (Keyconstance.is_user_account, NULL);//software has not kept account string UserPassword = USER
   Preference.read (Keyconstance.is_user_password, NULL);

   String userid = userpreference.read (keyconstance.is_user_id, NULL);
    if (Textutils.isempty (UserAccount)) {//No saved login information jumps to login interface//empty, indicates no registration, or clears data Intent Intent = new Intent ();
    Intent.setclass (Welcomeactiviy.this, Loginactivity.class);
    StartActivity (Intent); Overridependingtransition (Android. R.anim.slide_in_left, Android.
    R.anim.slide_out_right);
   Finish (); else {////login directly with the saved information (requestapidata.getinstance). Getlogindata (UserAccount, UserPassword, Userbaseinfo.clas

   s, welcomeactiviy.this); Welcomeactivity also implements the Httpresponecallback interface, so the incoming callback object is itself, and we determine in the callback method whether the login was successful @Override public void Onresponestart (String apiname) {} @Override public void onloading (string apiname, Long count, long current) {} @Over Ride public void onsuccess (String apiname, Object){///whether the current interface is an interface to get the user's basic information if (UrlConstance.KEY_USER_BASE_INFO.equals (apiname)) {if (object!= null && object in
   Stanceof userbaseinfo) {userbaseinfo info = (userbaseinfo) object; Itlanbaoapplication.getinstance (). Setbaseuser (Info)//Put the data into the application, the global Userpreference.save (

   keyconstance.is_user_id, String.valueof (Info.getuserid ()));
   Intent Intent = new Intent ();
   Intent.setclass (Welcomeactiviy.this, Mainactivity.class);
   StartActivity (Intent); Overridependingtransition (Android. R.anim.slide_in_left, Android.
   R.anim.slide_out_right);

  Finish ();
  else {toast.maketext (welcomeactiviy.this, "Load Failed", Toast.length_short). Show ();  } else if (UrlConstance.KEY_LOGIN_INFO.equals (apiname)) {//The current interface is the login interface//Login return Data if (object!= null && object
   instanceof Userbaseinfo) {userbaseinfo info = (userbaseinfo) object; if (Constant.KEY_SUCCESS.equals (Info.getret ())) {itlanbaoapplication.getinstance (). Setbaseuser (info);// Save user information in ApplicatIon Userpreference.save (keyconstance.is_user_id, String.valueof (Info.getuserid ()));
    Intent Intent = new Intent ();
    Intent.setclass (Welcomeactiviy.this, Mainactivity.class);
    StartActivity (Intent); Overridependingtransition (Android. R.anim.slide_in_left, Android.
    R.anim.slide_out_right);

   Finish ();
   else {toast.maketext (welcomeactiviy.this, Info.getmsg (), Toast.length_short). Show (); @Override public void OnFailure (string apiname, Throwable t, int errorno, string strMsg) {Toast.maketext (Wel
Comeactiviy.this, "failure", Toast.length_short). Show ();


 }

Demo Download Address :Http://xiazai.jb51.net/201611/yuanma/Androidlogindemo (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.