Reusing HttpURLConnection

In my application, I use the following code to upload multiple images. Is it high-performance for this way, or can I use it somehow?

for(int i = 0; i < 100; i++){ URL url = new URL("http://www.android.com/image" + i + ".jpg"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in); finally { urlConnection.disconnect(); } } } 
+6
source share
2 answers

You will not get any benefit from reusing HttpURLConnection .

One thing that will greatly benefit your application is to spend some time looking for Async Tasks , which allows you to use the power of multi-threaded HTTP requests with callbacks to your main code.

See: http://www.vogella.com/articles/AndroidPerformance/article.html for a good example of using Async Tasks.

A good starting point is, of course, the Android Developers Blog , where they have an example for downloading images from the server asynchronously, which will meet your requirements. With some adaptation, you can send your application to several asynchronous requests at once for good performance.

Google article can be found at: http://android-developers.blogspot.co.uk/2009/05/painless-threading.html

The key viewing area is:

 public void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png"); } private class DownloadImageTask extends AsyncTask { protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); } } 

The loadImageFromNetwork method is where the download is performed, and will be completely asynchronous from the main user interface thread.

As a basic example, you can modify your application to call it like this:

 for(int i = 0; i < 100; i++){ new DownloadImageTask().execute("http://www.android.com/image" + i + ".jpg"); } 

Although I would not choose 100 requests for optimization at once, perhaps by creating a queue system with threads that would allow 4 or 5 simultaneous connections, and then save the rest when the other finishes, supporting the ArrayList pending read requests.

+5
source

No matter how you do it, you will end up opening several connections to get each image. So any image is obtained. And there is no way to change the HttpURLConnection anyway. So it can look great in that sense.

However, you can try to upload multiple images at the same time using streaming. It would be more difficult to implement such a scheme, but it is quite possible. This will speed up the process by requesting multiple images at once.

0
source

All Articles