Basic learning of Android Network Technology (VII)

Source: Internet
Author: User

To access the network using the HttpClient protocol:

 Public classMainactivity extends Activity implements onclicklistener{ Public voidOnClick (View v) {if(V.getid () = =r.id.send_request)        {sendrequestwithhttpclients (); }    }    Private voidsendrequestwithhttpclients () {NewThread (NewRunnable () { Public voidrun () {Try{HttpClient HttpClient=NewDefaulthttpclient ();//Create an Defaulthttpclient instance, note that httpclient is an interface that cannot create an instance directlyHttpGet httpget=NewHttpGet ("URL"); Create HttpGet object HttpResponse HttpResponse=Httpclient.execute (HttpGet); if(Httpresponse.getstatusline (). Getstatuscode () = = $){//first remove the status code to determine if the request and response are successfulHttpentity entity=httpresponse.getentity ();//call GetEntity to get an instance and convert it into charactersString response=entityutils.tostring (Entity,"Utf-8"); Message Message=NewMessage (); Message.what=show_response; Message.obj=response.tostring ();                 Handler.sendmessage (message); }            }Catch(Exception e) {e.printstacktrace;}    }}). Start (); }}

Use Jsonobject to parse the data that the server responds to:

Private voidParsejsonwithjsonobject (String jsondata) {Try{Jsonarray Jsonarray=NewJsonarray (Jsondata);//passes the returned data into an array         for(intI=0; I<jsonarray.lenth (); i++) {Jsonobject jsonobject=jsonarray.getjsonobject (i);//call Getjsonobject to get the instance and then use GetString to remove the print.String id=jsonobject.getstring ("ID"); String name=jsonobject.getstring ("name"); String version=jsonobject.getstring ("version"); LOG.D ("mainactivity","ID is"+ID);                        .. }    }Catch(Exception e) {e.printstacktrace;}}

Best Practices for Network programming:
In order to be more convenient in the use of the common operation is extracted into the public class, and provide a static method, in order to prevent the request network time-out and affect the main thread is blocked, directly open the child thread and will not return data, so the Java callback mechanism is enabled

 Public Interfacehttpcallbacklistener{//The interface defines two methods that use OnFinish () to return the data of the response, OnError () when the network error is called    voidonfinish (String response); voidOnError (Exception e);} Public classhttputil{ Public Static voidsendhttprequest (Final String address,final Httpcallbacklistener listener) {NewThread (NewRunnable) {@Override Public voidrun () {httpurlconnection connection=NULL; Try{URL URL=NewURL (address); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); Connecion.setdoinput (true);                Connection.setdooutput (ture); InputStreaminch=Connecion.getinputstream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (inch)); Stringbuidler Response=NewStringbuidler ();                String Line;  while((Line=reader.readline ())! =NULL) {response.append (line); }                if(listener!=NULL) {listener.onfinish (response.tostring ()); }            }Catch(Exception e) {if(listener!=NULL) {listener.onerror ();} }finally{                if(connection!=NULL) {connection.disconnect ();    }}}}.start (); }} Special Note: If you need to update the UI based on the returned results, you must also use the asynchronous message processing mechanism, which onfinish actually runs in the child thread.

Basic learning of Android Network Technology (VII)

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.