Asyncactivity Loading Web pages asynchronously

Source: Internet
Author: User

Import Java.io.bufferedreader;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.url;import Java.net.urlconnection;import Java.util.zip.GZIPInputStream ; Import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.httpstatus;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.conn.clientconnectionrequest;import Org.apache.http.entity.bufferedhttpentity;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.params.basichttpparams;import Org.apache.http.params.httpconnectionparams;import Org.apache.http.util.entityutils;import Com.example.com.test.r;import Android.app.activity;import Android.os.asynctask;import Android.os.bundle;import Android.util.log;import andRoid.view.view;import Android.widget.button;import Android.widget.progressbar;import Android.widget.TextView; Import Android.widget.toast;public class Asyncactivity extends Activity {private button Satrtbutton;private button Cancelbutton;private ProgressBar progressbar;private TextView textview;private downloaderasynctask Downloaderasynctask; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.act_test06_async); Initview ();} public void Initview () {Satrtbutton = (button) Findviewbyid (R.id.startbutton); CancelButton = (Button) Findviewbyid ( R.id.cancelbutton); Satrtbutton.setonclicklistener (new Buttononclicklistener ()); Cancelbutton.setonclicklistener ( New Buttononclicklistener ());p Rogressbar = (progressBar) Findviewbyid (r.id.progressbar); TextView = (TextView) Findviewbyid (R.id.textview);} Private class Buttononclicklistener implements View.onclicklistener {public void OnClick (View v) {switch (V.getid ()) {CAs E r.id.startbutton://Note://1 Each time a new instance is required, the newly created task can only be executed once, otherwise an exception//2 instance of the asynchronous task must be created in the UI thread//3 The Execute () method must be called in the UI thread. Downloaderasynctask = new Downloaderasynctask ();d ownloaderasynctask.execute ("http://cn.jarfire.org"); break;case R.ID.CANCELBUTTON://cancels an executing task, the oncancelled () method will be called Downloaderasynctask.cancel (true); break;default:break;}}} Constructor Asynctask<params, Progress, result> parameter description://Params input parameters to start task execution//Progress background Task Execution progress//Result Type of background calculation result private class Downloaderasynctask extends Asynctask<string, Integer, string> {//OnPreExecute () The @overrideprotected method is used to prepare the main thread for some preparation work before performing an asynchronous task, such as void OnPreExecute () {super.onpreexecute (); Textview.settext (" Call the OnPreExecute () method---> Prepare to start executing the asynchronous task "); SYSTEM.OUT.PRINTLN ("Call the OnPreExecute () method---> Prepare to start executing the asynchronous task");} The Doinbackground () method is used to perform an asynchronous task, and you cannot change the main thread in ui@overrideprotected string Doinbackground (String ... params) { SYSTEM.OUT.PRINTLN ("Call the Doinbackground () method---> Start the Asynchronous Task"); try {return dohttpclient (Params[0]);} catch (Exception e) {return null;}} The OnPostExecute () method is used to perform an operation on the main thread after the asynchronous task execution completes @overrideprotected void OnPostExecute (String result) {Super.onpostexecute (result); Toast.maketext (Getapplicationcontext (), "Call OnPostExecute () method---> Asynchronous task execution Complete", 0). Show ();// TextView Display Network request result Textview.settext (result); System.out.println ("Call OnPostExecute () method---> Completion of Asynchronous Task");} The Onprogressupdate () method is used to update asynchronous execution in the main thread to handle the execution information of an asynchronous task @overrideprotected void Onprogressupdate (Integer ... values) { Super.onprogressupdate (values);//Change progress bar progressbar.setprogress (values[0]);//Change Textviewtextview.settext ("loaded" + Values[0] + "%");} The Oncancelled () method performs the associated operation in the main thread when the asynchronous task is canceled @overrideprotected void oncancelled () {super.oncancelled ();// Change the progress bar progress to 0progressbar.setprogress (0);//Change Textviewtextview.settext ("Call oncancelled () method---> Asynchronous task Canceled"); System.out.println ("Call oncancelled () method---> Asynchronous task Canceled");} Gets the data for the URL-------------------can normally use the private string dohttpclient (String urlstring) throws Clientprotocolexception, IOException, interruptedexception {basichttpparams httpparams = new Basichttpparams (); Httpconnectionparams.setconnectionTimeout (Httpparams, 6 * 1000); Httpconnectionparams.setsotimeout (Httpparams, 6 * 1000); HttpClient client = new Defaulthttpclient (httpparams);//Old method HttpGet get = new HttpGet (urlstring); HttpResponse response = Client.execute (get); System.out.println ("-----------------------"); System.out.println (Response.getstatusline ()); if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) { httpentity entity = response.getentity ();//-----------------------------Test string webcontent = ""; if (entity!=null) { entities = new bufferedhttpentity (entity);//In some cases it may be read more than once. At this point the entity content must be buffered in some way on memory or on disk. The simplest approach is to wrap the source entity through the use of the Bufferedhttpentity class. This causes the source entity content to be read into the memory buffer. In all other ways, the entity wrapper will get the source entity. WebContent = entityutils.tostring (entity); System.out.println ("Response getcontentlength:" + entity.getcontentlength ()); System.out.println ("Response toString () Length:" + webcontent.length ());} System.out.println (Response.tostring ()); Display HTTP request headerSystem.out.println ("----------------------------------------");//--------------------------------InputStream is = Entity.getcontent (), long total = 0;total = Entity.getcontentlength (); LOG.V ("AC", "total=" +total);  Bytearrayoutputstream BOS = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int count = 0;int length = -1;while (length = is.read (buffer))! =-1) {bos.write (buffer, 0, length); count + = length;//publishprogress () is a method in the Asynctask class//Often calls this method in Doinbackground ()// Used to notify the main thread of the execution of a background task.//This will trigger the Onprogressupdate () method log.v ("AC", "count/total=" +count+ "/" +total) in Asynctask; Publishprogress ((int) ((Count/(float) Total + 0.005f) * 100));//To demonstrate progress, hibernate 1000 Ms Thread.Sleep (1000);} Is.close (); return new String (Bos.tobytearray (), "UTF-8");} Get.abort (); Client.getconnectionmanager (). shutdown (); return null;} Open http Download Private InputStream openhttpconnection (String urlstring) throws IOException {//compressed file InputStream in = Null;in T response =-1; URL url = new URL (urlstring); URLConnection conn = Url.openconnection (); if (! ( Conn instanceof HttpURLConnection) {throw new IOException("It isn't an HTTP connection");} try {httpurlconnection httpconn = (httpurlconnection) conn;httpconn.setconnecttimeout (5*1000); Httpconn.setreadtimeout (5*1000); httpconn.setallowuserinteraction (false); Httpconn.setinstancefollowredirects ( true);//Httpconn.setrequestmethod ("GET");//In many websites, especially large web sites, it is necessary to set a request that must be a browser to respond. The reason for this is to prevent this kind of project from giving him a meaningless request (often this request is a large amount of load on its server). In order to solve this problem, we need to add properties to the HTTP request. Httpconn.setrequestproperty ("Charset", "UTF-8"), Httpconn.setrequestproperty ("Accept-encoding", "identity"); Httpconn.setrequestproperty ("accept-encoding", "gzip");//Why not deflate? As to why you should set up gzip without setting up deflate, for the following reasons, Some websites he doesn't care what compression format you can accept, it will also compress the content of the Web page to you. Of course IE,FF can handle these things well. So when we look through the browser it's perfectly normal. General gzip compression can be a 33K file compression into 7K, which will save a lot of bandwidth, but the server load does not reduce, because he wants to compress files AH. As for why not deflate, because most of the compression of the site is using gzip, and in some sites, is clearly used gzip return deflate compression logo. What is the point, so simply tell the server, I do not accept deflate, because he is too ugly, and long, which like gzip so tidal ah. Hehe, for a large number of static Web server, it is necessary to do so. 100M's exclusive server, he also only 100M AH. Httpconn.setrequestproperty ("Connection", "keep-alive");//keep-alive, what's the use of it, you're not on the site that you're collecting. Hey. Relieve the pressure of others, but alsois to relieve himself. Httpconn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 7.0; Windows NT 5.1);//This is set up, you can set your operating system value, browser value, version, as long as the correct is OK. This will allow the site to be accessed normally and effectively. He doesn't know if you're a browser. Even if you were a dog, he didn't know. Httpconn.setusecaches (false);//Do not use the cache, it is useless, because we do not often access to a link frequently. (for program) Httpconn.connect (); response = Httpconn.getresponsecode (); LOG.V ("AC", "Response:" +response); if (response = = HTTPURLCONNECTION.HTTP_OK) {in = Httpconn.getinputstream (); long x = Httpconn.getcontentlength (); LOG.V ("AC", "Total length:" +x);}} catch (Exception ex) {LOG.V ("Networking", Ex.getlocalizedmessage ()), throw new IOException ("Error connecting");} return in;}} /** * * @param urlconn * @param charset * @return */public static String getcontentfromin (HttpURLConnection urlconn, Stri Ng CharSet) {BufferedReader br = null; StringBuilder content = new StringBuilder, inputstream in = null;try {if (null = = Urlconn) {return "";} if (Isnotempty (urlconn.getcontentencoding ())) {String encode = urlconn.getcontentencoding (). toLowerCase (); if ( Isnotempty (Encode) && encode.indexof ("gzip") >= 0) {in = new Gzipinputstream (Urlconn.getinputstream ());}} if (null = = in) {in = Urlconn.getinputstream ();} if (null! = in) {br = new BufferedReader (new InputStreamReader (in, CharSet)); String line = "", while (line = Br.readline ())! = null) {content.append (line);}}} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if ( Null! = in) {try {in.close ();} catch (IOException e) {e.printstacktrace ();} in = null;} if (null! = BR) {try {br.close ();} catch (IOException e) {e.printstacktrace ();} in = null;}} return content.tostring ();} private static Boolean isnotempty (String str) {if (str.length () > 0) {return true;} return false;}}

Asyncactivity Loading Web pages asynchronously

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.