/*** Implementation of Asynctask, to fetch the data in the background away from * the UI thread. */ Private classDownloadtaskextendsAsynctask<string, Void, string>{@Overrideprotectedstring Doinbackground (String ... urls) {Try { returnLoadfromnetwork (urls[0]); } Catch(IOException e) {returngetString (R.string.connection_error); } } /*** Uses The logging framework to display the output of the fetch * operation in the log fragment. */@Overrideprotected voidOnPostExecute (String result) {log.i (TAG, result); } } /**initiates the fetch operation.*/ PrivateString Loadfromnetwork (String urlstring)throwsIOException {InputStream stream=NULL; String Str=""; Try{Stream=DownloadURL (urlstring); STR= Readit (Stream, 500); } finally { if(Stream! =NULL) {stream.close (); } } returnstr; } /*** Given A string representation of a URL, sets up a connection and gets * an input stream. * @paramurlstring A string representation of a URL. * @returnAn InputStream retrieved from a successful httpurlconnection. * @throwsjava.io.IOException*/ PrivateInputStream DownloadURL (String urlstring)throwsIOException {//begin_include (Get_inputstream)URL url =NewURL (urlstring); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setreadtimeout (10000/*milliseconds*/); Conn.setconnecttimeout (15000/*milliseconds*/); Conn.setrequestmethod ("GET"); Conn.setdoinput (true); //Start the queryConn.connect (); InputStream Stream=Conn.getinputstream (); returnstream; //end_include (Get_inputstream) } /**Reads An InputStream and converts it to a String. * @paramstream InputStream containing HTML from targeted site. * @paramlen Length of String, this method returns. * @returnString concatenated according to Len parameter. * @throwsjava.io.IOException *@throwsjava.io.UnsupportedEncodingException*/ PrivateString Readit (InputStream stream,intLenthrowsIOException, unsupportedencodingexception {reader Reader=NULL; Reader=NewInputStreamReader (Stream, "UTF-8"); Char[] buffer =New Char[Len]; Reader.read (buffer); return NewString (buffer); }
Invocation mode
New Downloadtask (). Execute ("http://www.google.com");
HttpURLConnection Encapsulating Asynchronous Network requests