1 PackageCom.exp.httpdemo;2 3 ImportJava.io.InputStream;4 5 Importorg.apache.http.HttpEntity;6 ImportOrg.apache.http.HttpResponse;7 Importorg.apache.http.client.HttpClient;8 ImportOrg.apache.http.client.methods.HttpGet;9 Importorg.apache.http.impl.client.DefaultHttpClient;Ten Importorg.apache.http.util.EntityUtils; One A ImportAndroid.os.Bundle; - ImportAndroid.os.Handler; - Importandroid.app.Activity; the ImportAndroid.view.Menu; - ImportAndroid.view.View; - ImportAndroid.widget.TextView; - + /** - * Request a webpage using httpclient + * A */ at Public classMainactivityextendsActivity { - TextView Tvresult; -String url= "Http://www.baidu.com"; -Handler Handler =NewHandler (); - @Override - protected voidonCreate (Bundle savedinstancestate) { in Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); to +tvresult=(TextView) Findviewbyid (r.id.textview1); - } the * Public voidClickbutton (view view) { $ NewThread (NewRunnable () {Panax Notoginseng - @Override the Public voidrun () { + //Get HttpClient Object AHttpClient HttpClient =Newdefaulthttpclient (); the //get HttpGet Object +HttpGet Requestget =Newhttpget (URL); - Try { $ //Get response Results $HttpResponse HttpResponse =Httpclient.execute (requestget); - if(Httpresponse.getstatusline (). Getstatuscode () = = 200) { - //Remove the entity class from the response theHttpentity httpentity =httpresponse.getentity (); - FinalString result=entityutils.tostring (httpentity);Wuyi //If you want to read and write through IO streams, you can use the GetContent method to obtain the //InputStream in = Httpentity.getcontent (); -Handler.post (NewRunnable () { Wu - @Override About Public voidrun () { $ Tvresult.settext (result); - } - }); - } A}Catch(Exception e) { + e.printstacktrace (); the - } $ } the }). Start (); the the the } - @Override in Public BooleanOncreateoptionsmenu (Menu menu) { the //inflate the menu; This adds items to the action bar if it is present. the getmenuinflater (). Inflate (R.menu.main, menu); About return true; the } the the}
Use HttpClient to request a Web page