download image from unformatted url [duplicate]

Try this code :

Create LocalImageSaver.java :

public class LocalImageSaver extends AsyncTask<Void, String, Boolean> {

    private final SaveCompletionInterface saveCompletionInterface;
    private final String originalImageUrl;
    private final Context context;
    private String savedImagePath;
    private String fUrl;

    public LocalImageSaver(Context context, String originalImageUrl, SaveCompletionInterface saveCompletionInterface) {
        this.context = context;
        this.saveCompletionInterface = saveCompletionInterface;
        this.originalImageUrl = originalImageUrl;
    }

    /**
     * Downloading file in background thread
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected Boolean doInBackground(Void... f_url) {

        this.fUrl = originalImageUrl;

        FileOutputStream output = null;
        InputStream is = null;
        try {

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(fUrl);
            HttpContext context = new BasicHttpContext();
            HttpResponse response = client.execute(get, context);
            is = response.getEntity().getContent();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200 && is != null) {
                String imageNameToSave;

                String extension = originalImageUrl.substring(originalImageUrl.lastIndexOf(".") + 1); // Without dot jpg, png
                if (extension.contains("mp4")) {
                    extension = "mp4";
                }

                String fileName = "";//originalImageUrl.substring(originalImageUrl.lastIndexOf("https://stackoverflow.com/") + 1); // Without dot jpg, png
                fileName = "05Media_" + Calendar.getInstance().getTimeInMillis() + "." + extension;
                imageNameToSave = fileName;


                Uri savedImagePathUri = CommonImageUtil.createImageFile(imageNameToSave);
                savedImagePath = savedImagePathUri.getPath();
                // Output stream to write file
                output = new FileOutputStream(savedImagePathUri.getPath());

                int read = 0;
                byte[] buffer = new byte[32768];
                while ((read = is.read(buffer)) > 0) {
                    output.write(buffer, 0, read);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                is.close();
                return true;
            }

        } catch (ClientProtocolException e) {
            Lg.printStackTrace(e);
        } catch (IOException e) {
            Lg.printStackTrace(e);
        } catch (Exception e) {
            Lg.printStackTrace(e);
        } finally {

            // flushing output
            try {
                if (output != null) {
                    output.flush();
                }
            } catch (IOException e) {
                Lg.printStackTrace(e);
            }
            try {
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
                Lg.printStackTrace(e);
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                Lg.printStackTrace(e);
            }
        }

        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        saveCompletionInterface.onSaved(result, savedImagePath);
    }

    public interface SaveCompletionInterface {
        public void onSaved(boolean result, String imageNameToSave);
    }
}

and call this :

        LocalImageSaver localImageSaver = new LocalImageSaver(getActivity(), url, new LocalImageSaver.SaveCompletionInterface() {
            @Override
            public void onSaved(boolean result, String savedImagePath) {

                if (result) {
                    //showToast(getActivity(), (R.string.image_save_succesfull));

                    // refresh gallery
                    try {
                        MediaScannerConnection.scanFile(getActivity(), new String[]{savedImagePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                            }
                        });
                    } catch (Exception e) {
                    }

                } else {
                    //showToast(getActivity(), (R.string.error_saving_image));
                }
            }

        });
        localImageSaver.execute();

Leave a Comment