Use of the Android post method

Source: Internet
Author: User

Java code

 PackageXidian.dy.com.chujia;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classMainactivityextendsappcompatactivity {String username;    String password; Handler Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Toast.maketext (mainactivity. This, (String) msg.obj, Toast.length_short). Show ();    }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button Submit=(Button) Findviewbyid (r.id.submit); if(Submit! =NULL) Submit.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {EditText Etuser=(EditText) Findviewbyid (r.id.username); EditText Etpass=(EditText) Findviewbyid (R.id.password); if(Etpass! =NULL&& Etuser! =NULL) {username=Etuser.gettext (). toString (); Password=Etpass.gettext (). toString (); LOG.I ("Login_username", username); LOG.I ("Login_password", password);            } login ();    }        }); }    Private voidLogin () {NewThread (NewRunnable () {@Override Public voidrun () {Try {URL url =NewURL ("http://192.168.0.162/test.php"); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("POST"); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000); StringBuilder SB=NewStringBuilder (); Sb.append ("Username="). Append (username). Append ("&password=").). append (password); Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); Conn.setrequestproperty ("Content-length", sb.length () + ""); //Open Input StreamConn.setdooutput (true); //Establish a connection//the sequence of connections and open streams cannot be confusedConn.connect (); OutputStream OS=Conn.getoutputstream ();                    Os.write (Sb.tostring (). GetBytes ()); //Get Server answer data                    if(Conn.getresponsecode () = = 200) {InputStream is=Conn.getinputstream (); String text=Utils.gettextfromstream (IS); Message msg=Handler.obtainmessage (); Msg.obj=text;                        Handler.sendmessage (msg);                    Is.close ();                } os.close (); } Catch(Exception e) {e.printstacktrace ();    }}). Start (); }}
Layout file
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns: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:orientation= "vertical"Tools:context= "Xidian.dy.com.chujia.MainActivity">        <RelativelayoutAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content">                <TextViewAndroid:id= "@+id/usr"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:textsize= "22SP"Android:text= "User name"/>                <EditTextAndroid:id= "@+id/username"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_torightof= "@+id/usr"/>        </Relativelayout>        <RelativelayoutAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content">                <TextViewAndroid:id= "@+id/p"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:textsize= "22SP"Android:text= "Password"/>                <EditTextAndroid:id= "@+id/password"Android:inputtype= "Textpassword"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_torightof= "@+id/p"/>        </Relativelayout>        <ButtonAndroid:id= "@+id/submit"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Submit"/></LinearLayout>
Tool class
 PackageXidian.dy.com.chujia;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;/*** Created by Dy on 2016/6/28.*/ Public classUtils { Public StaticString Gettextfromstream (InputStream is) {byte[] B =New byte[1024]; intLen = 0; //creates a byte array output stream and reads the text data of the input stream, synchronously writes the data to the array output streamBytearrayoutputstream BOS =NewBytearrayoutputstream (); Try {             while(len = Is.read (b))! =-1) {Bos.write (b,0, Len); }            //converts data in a byte array output stream into a byte arrayString Text =NewString (Bos.tobytearray ()); returntext; } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        return NULL; }}

Use of the Android post method

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.