Sun Microsystems SB related article is a good place to start. However, I would definitely not call this the preferred way. First, he throws an exception unnecessarily, then he does not close the threads at the end. In addition, it uses the url.openStream method, which I disagree with, since it can still receive output, even if an HTTP Error is returned .
Instead of url.openStream we write:
HttpURLConnection conn=(HttpURLConnection) url.openConnection() //Any response code starting with 2 is acceptable if(!String.valueOf(conn.getResponseCode()).startsWith('2')) //Provide a nice useful exception throw new IOException("Incorrect response code "+conn.getResponseCode()+" Message: " +getResponseMessage()); InputStream rawIn=conn.getInputStream() OutputStream rawOut=conn.getOutputStream() //You may want to add buffering to reduce the number of packets sent BufferedInputStream bufIn=new BufferedInputStream(rawIn); BufferedOutputStream bufOut=new BufferedInputStream(rawOut);
DO NOT USE THIS CODE WITHOUT PROCESSING EXCEPTIONS OR CLOSING FLOWS! . This is actually quite difficult to do correctly. If you want to see how to do it right, look at my answer to the much more specific question of selecting images in Android , since I do not want to rewrite all of this here.
Now, when you download input from the server, if you are not writing a command line tool, you need to run it in a separate stream and display the download dialog. Sgarman's answer demonstrates this using the main Java threads, and my answer to this question is using the AsyncTask class from Android to make it tidier . The class file has no dependencies on Android, and the license is Apache, so you can use it in projects other than Android.
source share