Post Submission Code
1 Public classMainactivityextendsActivity {2 3 @Override4 protected voidonCreate (Bundle savedinstancestate) {5 Super. OnCreate (savedinstancestate);6 Setcontentview (r.layout.activity_main);7 }8 9Handler Handler =NewHandler () {Ten Public voidhandlemessage (android.os.Message msg) { OneToast.maketext (mainactivity. This, (String) msg.obj, 0). Show (); A } - }; - the Public voidClick (View v) { -EditText Et_name =(EditText) Findviewbyid (r.id.et_name); -EditText Et_pass =(EditText) Findviewbyid (r.id.et_pass); - + FinalString name =Et_name.gettext (). toString (); - FinalString pass =Et_pass.gettext (). toString (); + AThread T =NewThread () { at @Override - Public voidrun () { - //the submitted data needs to be URL encoded, and the English and digital encoding will not change -@SuppressWarnings ("Deprecation") -String Path = "Http://192.168.13.13/Web2/servlet/LoginServlet"; - in Try { -URL url =NewURL (path); toHttpURLConnection conn =(HttpURLConnection) url.openconnection (); +Conn.setrequestmethod ("POST"); -Conn.setconnecttimeout (5000); theConn.setreadtimeout (5000); * $ //to stitch up the string of data to be submittedPanax NotoginsengString data = "Name=" + urlencoder.encode (name) + "&pass=" +Pass; - //add two line properties for a POST request theConn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); +Conn.setrequestproperty ("Content-length", data.length () + ""); A the //set open output stream +Conn.setdooutput (true); - //get the output stream $OutputStream OS =Conn.getoutputstream (); $ //using the output stream to submit data to the server - Os.write (Data.getbytes ()); - if(Conn.getresponsecode () = = 200){ theInputStream is =Conn.getinputstream (); -String Text =Utils.gettextfromstream (IS);Wuyi theMessage msg =handler.obtainmessage (); -Msg.obj =text; Wu handler.sendmessage (msg); - } About}Catch(Exception e) { $ //TODO auto-generated Catch block - e.printstacktrace (); - } - } A }; + T.start (); the - $ the } the the}
Utils
1 Public classUtils {2 3 Public StaticString Gettextfromstream (InputStream is) {4 5 byte[] B =New byte[1024];6 intLen = 0;7 //creates a byte array output stream and reads the text data of the input stream, synchronously writes the data to the array output stream8Bytearrayoutputstream BOS =NewBytearrayoutputstream ();9 Try {Ten while(len = Is.read (b))! =-1){ OneBos.write (b, 0, Len); A } - //converts data in a byte array output stream into a byte array -String Text =NewString (Bos.tobytearray ()); the returntext; -}Catch(IOException e) { - //TODO auto-generated Catch block - e.printstacktrace (); + } - return NULL; + } A}
Submit data using Post