Submission data for Android Day05-network programming

Source: Internet
Author: User
Tags response code
<span id="Label3"></p><p><p><span style="font-size:20px;color:rgb(112,48,160);"><strong><span style="font-size:20px;">I. Submission of data</span></strong></span></p></p><p><p>The principle of submitting data to the server by the mobile app is the same as when the Web page submits data to the server, relying on the HTTP association</p></p><p><p>The API is Different.<br></p></p><p><p>There are 3 classes of Android's most common submission Data: httpurlconnection, HttpClient, asynchttpclient, which</p></p><p><p>We all divide get and post two ways of submission where httpurlconnection is the Sdk's own class; HttpClient was originally a 3rd party open source</p></p><p><p>project, but was included in Google Sdk;asynchttpclient is a particularly simple to use 3rd party open source projects, need to go</p></p><p><p>GitHub downloads the jar Package.</p></p><p><p><br></p></p><p><p>I've Integrated 6 different submissions, and the App UI interface looks like This:</p></p><p><p>650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/6F/EC/wKiom1WtJVaQGXG-AACHnYU0azU088.jpg "title=" Device-2015-07-21-004428.png "alt=" wkiom1wtjvaqgxg-aachnyu0azu088.jpg "/><br></p></p><p><p>Here are the source code for submitting data in 6 different ways:</p></p><p><p><span style="color:rgb(255,0,0);">1) urlget Mode</span></p></p><p><p><span style="color:rgb(255,0,0);"><span style="color:rgb(0,0,0);">Urlget is characterized by stitching the request parameters directly behind the submission Address.</span><br></span></p></p><pre class="brush:java;toolbar:false">        // 1-in Urlget Way Public void loginbyurlget ()  {new thread ()  {public void run ()  {//  if username and account are not empty if  (checkempty ())  {//  has got the username and password, just take it with YOU. string servletpath =  "http://192.168.17.71/QQCenter/login";//  Stitching Address (********* Important step ********** ) string urlpath = servletpath +  "username="  + username+  "& password= " + password;try {//  1th step: Create Urlurl url = new url (urlpath);//   2nd step: Create httpurlconnection connection httpurlconnection conn =  (httpurlconnection)   Url.openconnection ();//  3rd step: Set Request parameters Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5);//  4th step: Get Response code Int responsecode = conn.getresponsecode ();//  5th step: Determine the response code if  (responsecode  == 200)  {//  Get the server-side return information Inputstream in = conn.getinputstream (); string content = Netutils.readstream (in); Showtoast (content); System.out.println ("urlget Mode landing");  else {showtoast ("the Server cannot find a resource");}}  catch  (exception e)  {e.printstacktrace (); showtoast ("server busy!!!" ");}}}}. Start ();}</pre><p><p><span style="color:rgb(255,0,0);">2</span> <span style="color:rgb(255,0,0);">) Urlpost Way</span> <span style="color:rgb(255,0,0);"> </span></p></p><p><p><span style="color:rgb(255,0,0);"><span style="color:rgb(0,0,0);">Urlpost is characterized by the submission of the parameters through the stream to the server, compared to the Urlget mode, more than two letterhead</span></span></p></p><p><p><span style="color:rgb(255,0,0);"><span style="color:rgb(0,0,0);">and set permissions to write the stream to the Server.</span></span></p></p><pre class="brush:java;toolbar:false">        public void loginbyurlpost ()  {new Thread ()  {public void run ()  {//  If the username and account are not empty if  (checkempty ())  {//  have been given the username password, Just take it and use it directly. string servletpath =  "http://192.168.17.71/QQCenter/login";//the parameters to write to the request Body (******* key step ******** ) string data =  "username="  + username +  "&password=" + password;try  {//  1th step: Create Urlurl url = new url (servletpath);//  2nd step: Create httpurlconnection connection httpurlconnection conn =  (httpurlconnection)  url.openconnection () ;//  3rd step: Set request parameter Conn.setrequestmethod ("POST") conn.setreadtimeout (5);//  Note Set two request header information (* * * * * * * * * * * * * * ) Conn.setrequestproperty ("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty (" Content-length ",  data.length () + " ");//  Set permissions to write the stream to the server (* * * * * * * * *) conn.setdooutput (true);// Get the output flow to the server to send the request body Data (* * * * * key steps ******) Outputstream ouT = conn.getoutputstream (); out.write (data.getbytes ()); out.close ();//  4th step: Get the response code int  Responsecode = conn.getresponsecode ();//  5th step: Judgment Response Code if  (responsecode == 200)   {//  Gets the server-side return information Inputstream in = conn.getinputstream (); String content = netutils.readstream (in); showtoast (content); in.close (); System.out.println ("landed in Urlpost mode");  else {showtoast ("the Server cannot find a resource");}}  catch  (exception e)  {e.printstacktrace (); showtoast ("server busy!!!" ");}}}}. Start ();}</pre><p><p><span style="color:rgb(255,0,0);"></span><span style="color:rgb(255,0,0);">3) Clientget</span> <span style="color:rgb(255,0,0);">Way</span> <span style="color:rgb(255,0,0);"> </span></p></p><p><p><span style="color:rgb(255,0,0);"><span style="color:rgb(0,0,0);">HttpClient This class, there are many differences compared to the httpurlconnection syntax. Package requests and responses separately</span></span></p></p><p><p><span style="color:rgb(0,0,0);">into</span> a class. Get the server data is a <span style="text-decoration:underline;color:rgb(255,0,0);">multilayer wrapper</span> , need to get the data of the entity httpentity, according to the entity</p></p><p><p>Then get the output stream of the Server.</p></p><pre class="brush:java;toolbar:false">        public void loginbyclientget ()  {new Thread ()  {public void run ()  {//  if the username and account are not empty if  (checkempty ())  {//  have been given the username and password, Just take it and use it directly. string servletpath =  "http://192.168.17.71/QQCenter/login";//  Stitching Address string data =   "username="  + username +  "&password=" + password; string url = servletpath +  "?"  + data;try {//  1th step: Create HttpClient object httpclient client = new  Defaulthttpclient ();//  2nd step: Create a GET Request object Httpget get = new httpget (url);//  3rd step: Execute GET request object, get response Object. Httpresponse response = client.execute (get);//  4th step: Get the response code int responsecode =  Response.getstatusline (). getstatuscode ();//  5th step: Determine the response code if  (RESPONSECODE&NBSP;==&NBSP;200)  {//   Get server-side return information   Unlike  url, you get the data entity First. Httpentity entity = reSponse.getentity ();//  The output stream inputstream in = entity.getcontent () that gets the service from the data entity; String content = netutils.readstream (in); showtoast (content); in.close (); System.out.println ("landed in Clientget mode");  else {showtoast ("the Server cannot find a resource");}}  catch  (exception e)  {e.printstacktrace (); showtoast ("server busy!!!" ");}}}}. Start ();}</pre><p><p><span style="color:rgb(255,0,0);"></span><span style="color:rgb(255,0,0);">4</span> <span style="color:rgb(255,0,0);">) Clientpost</span> <span style="color:rgb(255,0,0);">Way</span></p></p><p><p><span style="color:rgb(255,0,0);"><span style="color:rgb(0,0,0);">in a relatively clientget way, submitting data in this way is slightly more complex. When you create the Entity data for a post request, you</span></span></p></p><p><p><span style="color:rgb(255,0,0);"><span style="color:rgb(0,0,0);">Too many layers of packaging.</span><br></span></p></p><pre class="brush:java;toolbar:false">            public void  Loginbyclientpost ()  {new thread ()  {public void run ()  {//  If the user name and account number are not empty if   (checkempty ())  {//  already got username and password, just take it with YOU. string servletpath =  "http://192.168.17.71/QQCenter/login";//  Request body Data string data =   "username="  + username +  "&password=" + password; string url = servletpath;try {//  1th step: Create HttpClient object httpclient client =  new defaulthttpclient ();//  2nd step: Create a POST request object Httppost post = new httppost (url) ;//  the process of encapsulating the request parameters into the entity------a little more complicated list<namevaluepair> listpairs = new arraylist< Namevaluepair> ();                           //note that the value of name should be unified with the server   namevaluepair  pair1&Nbsp;= new basicnamevaluepair ("username",  username); Namevaluepair pair2 = new basicnamevaluepair ("password",  password); ListPairs.add ( pair1); Listpairs.add (pair2); Httpentity postdataentity = new urlencodedformentity (listpairs);p ost.setentity ( postdataentity);//  3rd step: perform POST request Httpresponse response = client.execute (post);//  4th step: Get the status code int statuscode = response.getstatusline (). getstatuscode ();//  5th step: Determine the status code if  ( STATUSCODE&NBSP;==&NBSP;200)  {//  entity httpentity respentity = response.getentity () to get data ;//  from the entity to get flow inputstream in = respentity.getcontent (); String content = netutils.readstream (in); showtoast (content); in.close (); System.out.println ("landed in Clientpost mode");  else {showtoast ("resource not found");}}  catch  (exception e)  {e.printstacktrace (); showtoast ("server busy!!!" ");}}};}. Start ();}</pre><p><p><span style="color:rgb(255,0,0);"></span><span style="color:rgb(255,0,0);">5</span> <span style="color:rgb(255,0,0);">) Asynchttpclientget</span> <span style="color:rgb(255,0,0);">Way</span></p></p><p><p><span style="color:rgb(255,0,0);"></span> before using this class, go to GitHub to download and guide this package com.loopj.android.http to the Project's src target</p></p><p><p>Recorded. There is also a very cool place to use asynchttpclient, which is that this class does not need to be used in child threads, so</p></p><p><p>You can also update the UI Directly. The request address directly writes the servlet, and does not need to splice parameters, because the parameters are written in the</p></p><p><p>Requestparams to the Object.</p></p><pre class="brush:java;toolbar:false">        public void loginbyasynchttpclientget ()  {//   If the user name and account is not empty if  (checkempty ())  {//  has been given a username password, just take it with YOU. string servletpath =  "http://192.168.1.109/QQCenter/login";try {asynchttpclient  Asynchttpclient = new asynchttpclient ();//create GET Request Parameters  RequestParams params =  New requestparams ();  params.put ("username",  username);  params.put ("password",  password); Asynchttpclient.get (getapplicationcontext (), servletpath, params, new  Asynchttpresponsehandler () {//request Success @overridepublic void onsuccess (int statuscode, header[]  headers,byte[] responsebody)  {if (statuscode == 200) {//get The return value of the server  String  Content = new string (responsebody); Toast.maketext (getapplicationcontext (),  content, 0). show (); System.out.println ("asynchttpclientget Mode landing"); Else{toast.maketext (geTapplicationcontext (),  "resource not found",  0). show ();}} @Overridepublic  void onfailure (int statuscode, header[] headers,byte[]  Responsebody, throwable error)  {// todo auto-generated method stub});}  catch  (exception e)  {e.printstacktrace (); showtoast ("server busy!!!" ");}}}</pre><p><p><span style="color:rgb(255,0,0);">6</span> <span style="color:rgb(255,0,0);">) Asynchttpclientpost</span> <span style="color:rgb(255,0,0);">Way</span></p></p><p><p><span style="color:rgb(255,0,0);"><span style="line-height:0px;"></span> similar to</span> asynchttpclientget, the Post method <span style="line-height:0px;"></span> is Called. The rest of the same<span style="line-height:0px;"></span><span style="color:rgb(255,0,0);"><span style="line-height:0px;"></span><br></span></p></p><pre class="brush:java;toolbar:false">          public void loginbyasynchttpclientpost ()  {//  if the user name and account is not empty if  (checkempty ())  {//  has been given a username password, just take it with YOU. string servletpath =  "http://192.168.17.71/QQCenter/login"; try {// Create Asynchttpclient Object Asynchttpclient asynchttpclient = new asynchttpclient ();  Requestparams params = new requestparams ();  params.put ("username",  username);  params.put ("password",  password); asynchttpclient.post (getapplicationcontext (),  servletpath,  params, new asynchttpresponsehandler () {@Overridepublic  void onsuccess (int  Statuscode, header[] headers,byte[] responsebody)  {if (statuscode == 200) {// Get the return value of the server  string content = new string (responsebody); Toast.maketext (getapplicationcontext (),  content, 0). show (); System.out.println ("asynchttpclientpost Mode landing"); ElsE{toast.maketext (getapplicationcontext (),  "resource not found",  0). show ();}} @Overridepublic  void onfailure (int statuscode, header[] headers,byte[]  Responsebody, throwable error)  {});}  catch  (exception e)  {e.printstacktrace (); showtoast ("server busy!!!" ");}}}</pre><p><p><span style="color:rgb(255,0,0);"><br></span><span style="color:rgb(112,48,160);">How to submit data, so many ways, how to use it? </span><br></p></p><p><p>HttpClient has been replaced by asynchttpclient, which is used in general Development. But when you meet special needs, you still need to<br></p></p><p><p>Use the most basic httpurlconnection, because it can set the parameter information of the request Header.<br></p></p><p><p><br></p></p><p><p><strong style="color:rgb(112,48,160);font-size:20px;white-space:normal;">second, the problem of Chinese garbled when submitting data</strong></p></p><p><p>For further understanding<br></p></p><p><p>This article is from the "line of the world" blog, please be sure to keep this source http://4259297.blog.51cto.com/4249297/1676565</p></p><p><p>Submission data for Android Day05-network programming</p></p></span>
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.