Android client interacts with server-side _android

Source: Internet
Author: User
Tags gettext response code stub tomcat server

This article together with you understand how the Android client and server interface is how to interact with the specific content as follows

1. Use a simple servlet in the background to support get or post. the servlet eventually returns to the foreground a string flag, the value is true or FALSE, indicating whether the login was successful.

The servlet needs to be configured before it is used, and the servlet-name of the servlet will be consistent with the servlet-name of servlet-mapping, otherwise the path cannot be found

I created a Web service project on MyEclipse and then deployed it to a Tomcat server for Android clients to access

<servlet> <servlet-name>helloWorld</servlet-name> <servlet-class>com.zhongzhong.wap.act Ion. helloservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloworld</ servlet-name> <url-pattern>/queryOrder</url-pattern> </servlet-mapping> 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 {@Override protected void doget (HttpServletRequest req, Httpservle

  Tresponse resp) throws Servletexception, IOException {doPost (req, resp); @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throwsServletexception, 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 created an Android project on the Android ADT, creating two activity, as a login interface and a successful login interface.

<relativelayout android:layout_height= "match_parent" android:layout_width= "Match_parent" Android:paddingbottom = "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "The @dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools:context= ". Mainactivity "xmlns:android=" http://schemas.android.com/apk/res/android "xmlns:tools=" http://schemas.android.com /tools "> <textview android:id=" @+id/textview1 "android:layout_alignparenttop=" true "Android:layout_ Centerhorizontal= "true" android:layout_height= "Wrap_content" android:layout_margintop= "40DP" android:layout_width = "Wrap_content" android:text= "HelloWorld Login Example" > <edittext android:ems= "android:hint=" Please enter account "android:id=" @+ Id/et_user "android:layout_below=" @+id/textview1 "android:layout_centerhorizontal=" true "android:layout_height=" Wrap_content "android:layout_margintop=" 33DP "android:layout_width=" wrap_content "> <requestfocus> </requestfocus></edittext> <edittext android:ems= "Ten" android:hint= "Please enter password" android: Id= "@+id/et_psw" android:inputtype= "Textpassword" android:layout_below= "@+id/et_user" Android:layout_ Centerhorizontal= "true" android:layout_height= "Wrap_content" android:layout_margintop= "40DP" android:layout_width = "Wrap_content" ><button android:id= "@+id/btn_login" android:layout_below= "@+id/et_psw" Android:layout_ Centerhorizontal= "true" android:layout_height= "Wrap_content" android:layout_margintop= "37DP" android:layout_width = "Wrap_content" android:text= "Landing" ></button></edittext></textview></relativelayout> &L T;relativelayout android:layout_height= "match_parent" android:layout_width= "Match_parent" @dimen/activity_vertical_margin "android:paddingleft=" @dimen/activity_horizontal_margin "android:paddingright=" @ Dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_vertical_margin "Tools:contExt= ". Naviactivity "xmlns:android=" http://schemas.android.com/apk/res/android "xmlns:tools=" http://schemas.android.com /tools "> <textview android:layout_alignparenttop=" true "Android:layout_centerhorizontal=" true "Android: layout_height= "Wrap_content" android:layout_margintop= "46DP" android:layout_width= "Wrap_content" android:text= "

 Landing Success "> </textview></relativelayout>

A 3.HTTP access public class for handling 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.DefaultHttpClient;

Import Org.apache.http.message.BasicNameValuePair;

 

Import Org.apache.http.util.EntityUtils;

Import android.content.Entity;

 

Import Android.util.Log;

  public class Httputil {//Create HttpClient object public static httpclient httpclient = new Defaulthttpclient ();

 

  public static final String base_url = http://192.168.3.14:8090/HelloWord/; /** * * @param URL * Send the requested URL * @return Server response String * @throws Exception/public static Stri

    ng getrequest (String url) throws Exception {//Create HttpGet object. Httpget get = new HttpGet (URL);

    Send GET request HttpResponse HttpResponse = Httpclient.execute (get); If the server succeeds in returning the response if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {//Get server response string string result

      = Entityutils.tostring (Httpresponse.getentity ());

    return result;

      else {LOG.D (server response code, (New Integer (Httpresponse.getstatusline (). Getstatuscode ())). ToString ());

    return null;

   }/** * * @param URL * Send requested URL * @param params * Request parameter * @return Server response string

      * @throws Exception */public static string postrequest (string url, map<string, string= "" > Rawparams)

    Throws Exception {//Create HttpPost object.

    HttpPost post = new HttpPost (URL);

    If the number of passing parameters is more, the passed parameters can be encapsulated list<namevaluepair> params = new arraylist<namevaluepair> (); For (String Key:rawParams.keySet ()) {//Encapsulation request parameter Params.add (new Basicnamevaluepair (Key, Rawparams. Get (key));

    //Set request parameter Post.setentity (new urlencodedformentity (params, UTF-8));

    Send POST request HttpResponse HttpResponse = Httpclient.execute (POST); If the server succeeds in returning the response if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {//Get server response string string result

      = Entityutils.tostring (Httpresponse.getentity ());

    return result;

  return null;



 }} </namevaluepair></namevaluepair></string,>

4.IntentService service, which is used in the background to handle time-consuming operations in a queued manner.

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} @Override protected void Onhandleintent (Intent Intent) {//T Odo auto-generated Method Stub/** * tested, intentservice inside is a time-consuming operation * Intentservice joins the requested intent in queues using queues , * Then open a worker thread (thread) to handle the intent in the queue * for asynchronous StartService requests, Intentservice will process the completion of one and then process the second/B 

    Oolean flag = false; 

    Gets the user name and password string username = Intent.getstringextra (username) of the mainline Cheng via intent; 

    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); 

    //define the method to send the request private Boolean Dologin (string Username, string password) {string strflag =; 

    Use map to encapsulate request parameters hashmap<string, string= "" > Map = new hashmap<string, string= "" > (); 

    Map.put (UN, username); 

    Map.put (pw, password); Defines the URL String URL that sends the request = Httputil.base_url + queryorder?un= + username + &pw= + password; Get Way//String URL = httputil.base_url + loginservlet; 

    Post method log.d (URL, url); 

    LOG.D (username, username); 

    LOG.D (password, password); try {//Send request Strflag = httputil.postrequest (URL, map);//post mode//strflag = httputil.getrequest (ur L); 

    Get mode 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;

 }} </string,></string,>

5. Register Intentservice in Androidmanifest.xml. Note the Uses-permission node, which opens access to the network for the program.

<!--? XML version=1.0 encoding=utf-8?-->

<manifest android:versioncode= "1" android:versionname= "1.0" Package= "Com.example.logindemo" xmlns:android= "http://schemas.android.com/apk/res/android" >

 

  <uses-sdk android:minsdkversion= "8" android:targetsdkversion= ">

 

  <uses-permission android:name=" Android.permission.INTERNET ">

 

   

     

      <intent-filter>

         

 

        <category android:name=" Android.intent.category.LAUNCHER ">

      </category></action></intent-filter>

    </ activity>

     

    </activity>

 

    <service android:name= "Com.example.logindemo.ConnectService" >

    </service>

  </application>

 

</uses-permission></uses-sdk></manifest >

6. Landing interface Processing, attention

Button listener event, use the value intent will pass to the service. In the Receiving broadcast class, the same value that intent will pass is passed to the next activity. In OnCreate (), dynamically registers the instance receiver that receives the broadcast class. In the Receiving broadcast class, do not forget to log off the receiver after use, otherwise will report A are you missing a called to Unregisterreceiver ()? The exception.

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;

 

Import Android.widget.Toast; public class Mainactivity extends activity {private static final String action_recv_msg = Com.example.logindemo.actio

  N.receive_message;

  Private Button loginbtn;

  Private EditText Et_username;

  Private EditText Et_password;

  Private String UserName;

  Private String PassWord;

  Private Messagereceiver receiver;

    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

    Setcontentview (R.layout.activity_main);

    Initview (); Dynamic Registration Receiver IntentfilterFilter = new Intentfilter (action_recv_msg);  

    Filter.addcategory (Intent.category_default);  

    Receiver = new Messagereceiver ();

  Registerreceiver (receiver, filter); private void Initview () {//TODO auto-generated method Stub et_username = (EditText) Findviewbyid (r.id

    . Et_user);

    Et_password = (edittext) Findviewbyid (R.ID.ET_PSW);

    LOGINBTN = (Button) Findviewbyid (R.id.btn_login);

        Loginbtn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { TODO auto-generated Method Stub if (Matchloginmsg ()) {//if validation succeeds Intent Msgin 

          Tent = new Intent (mainactivity.this, Connectservice.class); 

          Msgintent.putextra (username, Et_username.gettext (). toString (). Trim ()); 

          Msgintent.putextra (password, Et_password.gettext (). toString (). Trim ());

        StartService (msgintent);

  }

         

      }

    }); } protected Boolean matchloginmsg () {//TODO auto-generated method Stub userName = Et_username.gettext (). toString (). Trim ()

    ;

    PassWord = Et_password.gettext (). toString (). Trim ();

      if (Username.equals ()) {Toast.maketext (mainactivity.this, account cannot be empty, toast.length_short). Show ();

    return false;

      } if (Password.equals ()) {toast.maketext (mainactivity.this, password cannot be empty, toast.length_short). Show ();

    return false;

  return true; ///Receive broadcast classes public class Messagereceiver extends Broadcastreceiver {@Override public void onreceive (C  

      Ontext context, Intent Intent) {String message = Intent.getstringextra (result); 

    LOG.I (messagereceiver, message); If the login succeeds if (Message.equals (True)) {//Starts main activity Intent nextintent = new Intent (mainact 

        Ivity.this, Naviactivity.class); 

        StartActivity (nextintent); 

        End the activity finish (); 

   Logout broadcast Receiver     Context.unregisterreceiver (this);

      }else{Toast.maketext (mainactivity.this, username or password is incorrect, please re-enter!,toast.length_short). Show (); @Override public boolean Oncreateoptionsmenu (Menu menu) {//inflate the menu; thi

    s adds items to the action bar if it is present.

    Getmenuinflater (). Inflate (R.menu.main, menu);

  return true;
 }

 

}

The above is the entire content of this article, I hope to help you learn.

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.