Login example of interaction between Android client and server

Source: Internet
Author: User

Login example of interaction between Android client and server

Today, I learned how the android client interacts with the server, and found that it is actually a bit similar to the web. Then I found a logon example on the Internet based on IntentService.

 

1. Simple servlet is used in the background, and GET or POST is supported. The servlet returns a flag string to the front-end. The value is true or false, indicating whether the logon is successful.

The servlet must be configured before use. The servlet-name of the servlet must be consistent with the servlet-name of servlet-mapping. Otherwise, the path cannot be found.

I created a web service Project on myEclipse and deployed it on the tomcat server for the android client to access

 

 
  
   helloWorld
  
  
   com.zhongzhong.wap.action.HelloServlet
  
 
 
  
   helloWorld
  
  
   /queryOrder
  
 


 

 

import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.zhongzhong.wap.bean.UserBean;public class HelloServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { resp.setContentType(text/html);          PrintWriter out = resp.getWriter();          Boolean flag = false;            String userName = req.getParameter(un);          String password = req.getParameter(pw);           if(userName.equals(htp)&&password.equals(123))        {        flag = true;        }                else flag = false;        System.out.println(userName:+userName+ password:+password);        out.print(flag);          out.flush();          out.close(); }}

2. Then I create an android project on the android ADT and create two activities as the logon interface and logon success interface respectively.

 

 

     
      
           
        
    
       
   
    
   
  
 

     
  
 


 

3. Public class for HTTP access, used to process GET and POST requests

 

Package com. example. logindemo; import java. util. arrayList; import java. util. list; import java. util. map; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. client. httpClient; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. httpGet; import org. apache. http. client. methods. httpPost; import org. apache. http. impl. client. D EfaultHttpClient; import org. apache. http. message. basicNameValuePair; import org. apache. http. util. entityUtils; import android. content. entity; import android. util. log; public class HttpUtil {// create the HttpClient object public static HttpClient httpClient = new DefaultHttpClient (); public static final String BASE_URL = http: // 192.168.3.14: 8090/HelloWord /; /***** @ param url * request URL * @ return server response string * @ throws Exce Ption */public static String getRequest (String url) throws Exception {// create an HttpGet object. HttpGet = new HttpGet (url); // send the get request HttpResponse httpResponse = httpClient.exe cute (GET); // if the server returns the response if (httpResponse. getStatusLine (). getStatusCode () = 200) {// obtain the server response String result = EntityUtils. toString (httpResponse. getEntity (); return result;} else {Log. d (Server Response Code, (new Integer (httpResponse. getStatusLine (). getStatusCode ())). toString (); return null ;}} /***** @ param url * request URL * @ param params * request parameter * @ return server response String * @ throws Exception */public static String postRequest (String url, map
 
  
RawParams) throws Exception {// create an HttpPost object. HttpPost post = new HttpPost (url); // if the number of parameters passed is large, you can encapsulate the List of parameters passed.
  
   
Params = new ArrayList
   
    
(); For (String key: rawParams. keySet () {// encapsulate the request parameter params. add (new BasicNameValuePair (key, rawParams. get (key);} // sets the request parameter post. setEntity (new UrlEncodedFormEntity (params, UTF-8); // send the POST request HttpResponse httpResponse = httpClient.exe cute (post); // if the server returns response if (httpResponse. getStatusLine (). getStatusCode () = 200) {// obtain the server response String result = EntityUtils. toString (httpResponse. getEntity (); return result;} return null ;}}
   
  
 

4. IntentService, used to process time-consuming operations in the backend in queue mode.

 

 

Package com. example. logindemo; import java. util. hashMap; import android. app. intentService; import android. content. intent; import android. util. log; public class ConnectService extends IntentService {private static final String ACTION_RECV_MSG = com. example. logindemo. action. RECEIVE_MESSAGE; public ConnectService () {super (TestIntentService); // TODO Auto-generated constructor stub} @ Overrideprotected void onHandleIntent (Intent intent) {// TODO Auto-generated method stub/*** after testing, IntentService can perform time-consuming operations * IntentService adds the requested Intent to the queue by queue, * enable a worker thread to process Intent in the queue * for asynchronous startService requests, IntentService processes the second request after completing one operation */Boolean flag = false; // use intent to obtain the username and password String sent from the main thread String username = intent. getStringExtra (username); String password = intent. getStringExtra (password); flag = doLogin (username, password); Log. d (LOGIN result, flag. toString (); Intent broadcastIntent = new Intent (); broadcastIntent. setAction (ACTION_RECV_MSG); broadcastIntent. addCategory (Intent. CATEGORY_DEFAULT); broadcastIntent. putExtra (result, flag. toString (); sendBroadcast (broadcastIntent);} // defines the request sending method private Boolean doLogin (String username, String password) {String strFlag =; // use Map to encapsulate the request parameter HashMap
 
  
Map = new HashMap
  
   
(); Map. put (un, username); map. put (pw, password); // defines the URL String url of the request to be sent = HttpUtil. BASE_URL + queryOrder? Un = + username + & pw = + password; // GET method // String url = HttpUtil. BASE_URL + LoginServlet; // POST Log. d (url, url); Log. d (username, username); Log. d (password, password); try {// send the request strFlag = HttpUtil. postRequest (url, map); // POST method // strFlag = HttpUtil. getRequest (url); // GET Log. d (server return value, strFlag);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} if (strFlag. trim (). equals (true) {return true;} else {return false ;}}}
  
 

5. Register IntentService in AndroidManifest. xml. Note that the uses-permission node enables the program to access the network.

 

 

 
     
      
                           
                                    
                 
     
                                    
            
        
   
  
 

6. Handle the login interface. Note that

 

 

  1. In button listening events, use Intent to pass the value to the service. In the receiving broadcast class, the value to be passed by Intent is also used to pass to the next Activity. In onCreate (), dynamically register the receiver for the broadcast class. Do not forget to log out of the receiver after the listener is used. Otherwise, a "Are you missing a call to unregisterReceiver ()" message will be reported ()? .

     

     

    Package com. example. logindemo; import android. OS. bundle; import android. app. activity; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. util. log; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; impor T android. widget. toast; public class MainActivity extends Activity {private static final String ACTION_RECV_MSG = com. example. logindemo. action. RECEIVE_MESSAGE; private Button loginBtn; private EditText et_username; private EditText et_password; private String userName; private String passWord; private encrypted volume er; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (s AvedInstanceState); setContentView (R. layout. activity_main); initView (); // dynamically register javaser IntentFilter filter = new IntentFilter (ACTION_RECV_MSG); filter. addCategory (Intent. CATEGORY_DEFAULT); receiver = new MessageReceiver (); registerReceiver (filter);} private void initView () {// TODO Auto-generated method stubet_username = (EditText) findViewById (R. id. et_user); et_password = (EditText) findViewB YId (R. id. et_psw); loginBtn = (Button) findViewById (R. id. btn_login); loginBtn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubif (matchLoginMsg ()) {// If Intent msgIntent = new Intent (MainActivity. this, ConnectService. class); msgIntent. putExtra (username, et_username.getText (). toString (). trim (); msgIntent. putExtra (password, et_passwor D. getText (). toString (). trim (); startService (msgIntent) ;}});} protected boolean matchLoginMsg () {// TODO Auto-generated method stubuserName = et_username.getText (). toString (). trim (); passWord = et_password.getText (). toString (). trim (); if (userName. equals () {Toast. makeText (MainActivity. this, account cannot be blank, Toast. LENGTH_SHORT ). show (); return false;} if (passWord. equals () {Toast. makeText (MainActivity. this, password cannot be blank, Toast. LENGTH_SHORT ). show (); return false;} return true;} // receives broadcast class public class MessageReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {String message = intent. getStringExtra (result); Log. I (MessageReceiver, message); // if the logon is successful if (message. equals (true) {// start Main Activity Intent nextIntent = new Intent (MainActivity. this, NaviActivity. class); startA Ctivity (nextIntent); // end the Activity finish (); // deregister the broadcast receiver context. unregisterReceiver (this);} else {Toast. makeText (MainActivity. this indicates that the user name or password is incorrect. enter a new one !, Toast. LENGTH_SHORT ). show () ;}}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}


     

    Run:

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.