Android client-server interaction login example, android example

Source: Internet
Author: User
Tags response code

Android client-server interaction login example, android example

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

<servlet><servlet-name>helloWorld</servlet-name><servlet-class>com.zhongzhong.wap.action.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 {@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.

<RelativeLayout 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: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <TextView android: id =" @ + id/textView1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentTop =" true "android: layout_centerHorizontal = "true" android: layout_marginTop = "40dp" android: text = "HelloWorld logon example"/> <EditText android: id = "@ + id/et_user" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_below = "@ + id/textView1" android: Rule = "true" android: layout_marginTop = "33dp" android: EMS = "10" android: hint = "Enter the Account"> <requestFocus/> </EditText> <EditText android: id = "@ + id/et_psw" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_below = "@ + id/et_user" android: Rule = "true" android: layout_marginTop = "40dp" android: EMS = "10" android: hint = "enter the password" android: inputType = "textPassword"/> <Button android: id = "@ + id/btn_login" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_below = "@ + id/et_psw" android: Rule = "true" android: layout_marginTop = "37dp" android: text = "login"/> </RelativeLayout>

<RelativeLayout 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: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". naviActivity "> <TextView android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentTop =" true "android: layout_centerHorizontal =" true "android: layout_marginTop = "46dp" android: text = ""/> </RelativeLayout>


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 Ex Ception */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 * The request URL * @ p Aram params * request parameter * @ return server response String * @ throws Exception */public static String postRequest (String url, Map <String, String> rawParams) throws Exception {// create an HttpPost object. HttpPost post = new HttpPost (url); // if the number of passed parameters is large, you can encapsulate the List of passed parameters <NameValuePair> params = new ArrayList <NameValuePair> (); 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 the 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/*** tested, intentService can perform time-consuming operations * IntentService adds the requested Intent to the queue using the queue method, * and then starts a worker thread (thread) to process Intent * in the queue for asynchronous startService requests, IntentService will process the second */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 = doL Ogin (username, password); Log. d ("Logon 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 <S Tring, String> map = new HashMap <String, String> (); 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"; // Log in POST mode. 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.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.logindemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <uses-permission android:name="android.permission.INTERNET" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.logindemo.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity            android:name="com.example.logindemo.NaviActivity"            android:label="@string/title_activity_navi" >        </activity>        <service android:name="com.example.logindemo.ConnectService" >        </service>    </application></manifest>

6. Handle the login interface. Note that

  1. In button listening events, use Intent to pass the value to the service.
  2. In the receiving broadcast class, the value to be passed by Intent is also used to pass to the next Activity.
  3. In onCreate (), dynamically register the receiver for the broadcast class.
  4. 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 cipher er; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (SavedInstanceState); 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) findVie WById (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_p Assword. 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, "the 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, NaviAct Ivity. class); startActivity (nextIntent); // end the Activity finish (); // deregister the broadcast receiver context. unregisterReceiver (this);} else {Toast. makeText (MainActivity. this, "the user name or password is incorrect. Please enter it again! ", 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:



Reprinted from http://blog.csdn.net/softwave


Want to learn about Data Interaction Between the android client and the server? For example, how to log on? How to read data from the server and display it on the client

Sign-1 integer. The highest digit is 1, indicating a negative number, but the stored computer? In the form of supplement-1 The actual storage format is 11111111. If your client reads and saves the unsigned integer, of course, 255 of the Code is a simple return value check, best server and client byte stream reading and writing. Hope to help you. Thank you for choosing

Server-side development that interacts with Android clients

C/S.
B/S. The Client can parse the returned data.
B/S, JAVA PHP ASP. NET can all
XML return, JSON return can all be

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.