Android Legacy HTTP request Get----POST method submit data (contains garbled problem)

Source: Internet
Author: User

1. Imitate the login page display (using the traditional method is process-oriented)

Using the HttpClient API provided by Apache is an object-oriented

(To solve the problem of Chinese garbled, mainly in 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);}


Android Client

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, access to the network must be accessed by a child thread, and permissions are involved, remember to add access to the network

In the following code, I write get and post two ways of threading requests ..... 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, "User name and password cannot be empty", Toast.length_short). Show ();        Return        }//Use the traditional get mode for the request server//New Thread_get (). Start (); Request server new Thread using the traditional post method_post (). Start ();                }//Traditional post mode 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 and 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 that the connection server successfully returned the message String data = Servertools.getinfo (conn.getinputst                    Ream ());                    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, "utf-                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 that the connection server successfully returned the message String data = Servertools.getinfo (conn.getinputst                    Ream ());                    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 (); }        }    }}


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



The source code for Android 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



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Legacy HTTP request Get----POST method submit data (contains garbled problem)

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.