1. Imitate the login page display (using the traditional method is process-oriented)
Using the HttpClient API provided by Apache is an object-oriented
(The bottom of the article contains the source of the connection, including the use of the async framework)
(Solve the problem of Chinese garbled.) The main is the Chinese data URL encoding)
The default encoding for Android phones is UTF-8
2. Mobile Demo
3.server
The code is as follows:
Server-side code:
Test Android device Log in public class login extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {String username = request.getparameter ("username") ; String Password = request.getparameter ("password");//encode data to solve garbled problem username = new string (Username.getbytes (" Iso-8859-1 ")," UTF-8 "); System.out.println ("username--:" +username+ "---Password:" +password); if (Username.equals ("admin") && Password.equals ("123")) {Response.getoutputstream (). Write ("Login succeeded". GetBytes ("UTF-8"));} Else{response.getoutputstream (). Write ("Login failed". GetBytes ("UTF-8"));}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Request.setcharacterencoding ("UTF-8");d Oget (request, response);}
Androidclient
Part of the layout file:
Test Android device Log in public class login extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {String username = request.getparameter ("username") ; String Password = request.getparameter ("password");//encode data to solve garbled problem username = new string (Username.getbytes (" Iso-8859-1 ")," UTF-8 "); System.out.println ("username--:" +username+ "---Password:" +password); if (Username.equals ("admin") && Password.equals ("123")) {Response.getoutputstream (). Write ("Login succeeded". GetBytes ("UTF-8"));} Else{response.getoutputstream (). Write ("Login failed". GetBytes ("UTF-8"));}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Request.setcharacterencoding ("UTF-8");d Oget (request, response);}
Activity Code section:
(Note: After android4.0, the network must have access to a child thread, and it involves permissions.) Remember to add access to the network
In the following code, I write a get and post two way thread request:
。。。。。
。。。
。。。 Slowly realize
)
public class Mainactivity extends Appcompatactivity {private static final int SUCCESS = 0; private static final int faile = 1; private static final int net_error = 3; private static final String TAG = "mainactivity"; EditText Et_username; EditText Et_password; TextView Show_result; String username; String password; Final String Path = "Http://188.188.7.85/Android_Server/Login"; Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {int = m Sg.what; Switch (what) {case success:string data = (String) msg.obj; Show_result.settext (data); Break Case FAILE:Toast.makeText (mainactivity.this, "Connection Server failed", Toast.length_short). Show (); Break Case NET_ERROR:Toast.makeText (mainactivity.this, "Network Exception", Toast.length_short). Show (); Break Default:break; } } }; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Et_username = (EditText) Findviewbyid (r.id.et_username); Et_password = (EditText) Findviewbyid (R.id.et_password); Show_result = (TextView) Findviewbyid (R.id.show_result); Username = Et_username.gettext (). toString (). Trim (); Password = Et_password.gettext (). toString (). Trim (); public void Login (view view) {username = Et_username.gettext (). toString (). Trim (); Password = Et_password.gettext (). toString (). Trim (); if (Textutils.isempty (username) | | Textutils.isempty (password)) {Toast.maketext (this, "username and password cannot be empty", Toast.length_short). Show (); Return }//Request server//new Thread_get () using the traditional Get method. Start (); Request Serv using the traditional post methodER new Thread_post (). Start (); }//Traditional post method request Server-side class Thread_post extends Thread {@Override public void run () {try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); 1. Set the request mode Conn.setrequestmethod ("POST"); Conn.setconnecttimeout (5000); The timeout event for setting the connection is 5 seconds//2. To combine data, be sure to URL-encode the data String commitdata = "Username=" +urlencoder.encode (user Name, "UTF-8") + "&password=" +urlencoder.encode (password, "UTF-8"); 3. Specify Content-type-actually the data type of the specified transfer conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded") ; 4. Specify Content-length content-length: Length of data conn.setrequestproperty ("Content-length", commitdata.length () + ""); 5. Open the output stream. Tell the server that I want to write the data conn.setdooutput (TRUE); 6. Start writing data OutputStream OS = Conn.getoutputstream (); Os.write (Commitdata.getbytes ());//Os.close (); int code = Conn.getresponsecode (); Gets the success code returned by LOG.I (TAG, "code:---" + code); if (code = = 200) {//Indicates the successful return of the connection server information String data = Servertools.getinfo (Conn.getinpu TStream ()); LOG.I (TAG, "Data:---" + data); Use the message processing mechanism to pass data to the main thread message ms = new Message (); Ms.what = SUCCESS; Ms.obj = data; Handler.sendmessage (MS); } else {//uses a message processing mechanism to pass data to the main thread message ms = new Message (); Ms.what = Faile; Handler.sendmessage (MS); }} catch (Exception e) {//Use the message processing mechanism to pass data to the main thread message ms = new Message (); Ms.what = Net_error; Handler.sendmessage (MS); E.printstacktrace (); }}}//Traditional Get mode Request server-side class Thread_get extends Thread {@Override public void run () { try {String GetPath = path + "? Username=" + urlencoder.encode (username, "U TF-8 ") +" &password= "+ urlencoder.encode (password," UTF-8 "); URL url = new URL (getpath); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); The timeout event for setting the connection is 5 seconds int code = Conn.getresponsecode (); Gets the success code returned by LOG.I (TAG, "code:---" + code); ; if (code = = 200) {//Indicates the successful return of the connection server information String data = Servertools.getinfo (Conn.getinpu TStream ()); LOG.I (TAG, "Data:---" + data); Use the message processing mechanism to pass data toMain thread Message ms = new Message (); Ms.what = SUCCESS; Ms.obj = data; Handler.sendmessage (MS); } else {//uses a message processing mechanism to pass data to the main thread message ms = new Message (); Ms.what = Faile; Handler.sendmessage (MS); }} catch (Exception e) {//Use the message processing mechanism to pass data to the main thread message ms = new Message (); Ms.what = Net_error; Handler.sendmessage (MS); E.printstacktrace (); } } }}
Tool class:
public class Servertools { //Get stream data from server to convert to text file public static String GetInfo (InputStream in) { //write data stream in memory Bytearrayoutputstream RAF = new Bytearrayoutputstream (); String data = null; try{ byte[] bt = new byte[1024]; int Len =0; while (len = In.read (BT))! =-1) { raf.write (Bt,0,len); } data = Raf.tostring (); } catch (Exception e) { e.printstacktrace (); } return data;} }
Android's source code is already on GitHub:
Traditional way Demo Address: Https://github.com/momxmo/HTTP_get_post
Apache provides an object-oriented approach to the HttpClient API Demo:https://github.com/momxmo/httpclient_get_post
HTTP requests using the Async-http-master pop-up framework: Https://github.com/momxmo/Http_android-async-http-master_Demo
????
Android Legacy HTTP request Get----POST method to submit data (including garbled issues)