ANDROID: download image/media files using HTTPCLIENT in android , using ASYNC TASK
2 min readApr 16, 2020
AndroidHttpClient is natively used to download file in this program. it is configured with network connection and socket timeout parameters. we have allowed redirection using HttpParams.
Below is the android async task for downloading any media file like video , audio, image etc.
MediaDownloadTaskListener - listener used to notify when downloading completes via onComplete() interface.NETWORK_CONNECTION_TIMEOUT - http connection timeout.NETWORK_SOCKET_TIMEOUT - http socket timeout.
public class MediaDownloadTask extends AsyncTask<String, Void, Boolean> { private static final int MAX_VIDEO_SIZE = 25 * 1024 * 1024; // 25 MiB
private static final int MAX_AUDIO_SIZE = 5 * 1024 * 1024; // 5MB
public interface MediaDownloadTaskListener {
/**
* notify on finish
*
* @param isSuccessful
*/
void onComplete(boolean isSuccessful); }
private final MediaDownloadTaskListener mMediaDownloadTaskListener; public MediaDownloadTask(final MediaDownloadTaskListener listener) {
mMediaDownloadTaskListener = listener;
} @Override
protected Boolean doInBackground(final String... params) { if (params == null || params.length == 0 || params[0] == null) {
return false;
}
for (int argc = 0; argc < params.length; argc++) {
final String mediaFileUrl = params[argc];
AndroidHttpClient httpClient = null;
try {
httpClient = getHttpClient();
final HttpGet httpget = new HttpGet();
httpget.setHeader(USER_AGENT, Settings.getSettings().getUserAgent());
httpget.setURI(new URI(COHttpUtils.getFinalEncodedUrl(mediaFileUrl)));
final HttpResponse response = httpClient.execute(httpget); if (response == null || response.getEntity() == null) {
throw new IOException("Obtained null response from url: " + mediaFileUrl);
} if (response.getEntity().getContentLength() > MAX_VIDEO_SIZE) {
throw new IOException("exceeded max download size");
} final InputStream inputStream = new BufferedInputStream(response.getEntity().getContent());
diskPutResult = CacheService.putToDiskCache(mediaFileUrl, inputStream);
inputStream.close();
} catch (Throwable e) {
//retry is not handled
Log.internal("", "Failed to download : " + e.getMessage());
return false;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
}
return diskPutResult;
} public static AndroidHttpClient getHttpClient() {
AndroidHttpClient httpClient = AndroidHttpClient.newInstance(Settings.getSettings().getUserAgent());
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, NetworkSettings.NETWORK_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, NetworkSettings.NETWORK_SOCKET_TIMEOUT);
HttpClientParams.setRedirecting(params, true);
return httpClient;
} @Override
protected void onCancelled() {
onPostExecute(false);
} @Override
protected void onPostExecute(final Boolean isSuccessful) {
if (mMediaDownloadTaskListener != null) {
mMediaDownloadTaskListener.onComplete(isSuccessful);
}
}
}