MalformedURLException в android при загрузке файла zip - PullRequest
0 голосов
/ 15 декабря 2011

Я загружаю zip-архив в android и получаю следующие ошибки.

InputStream Connection - нулевое исключение, выброшено

java.net.MalformedURLException: Protocol not found: www.songspk320.in/128/indian/Don-2-2011-128Kbps(Songs.PK).zip
    at java.net.URL.<init>(URL.java:273)
    at java.net.URL.<init>(URL.java:157)
    at com.linkezzi.web.DownloadIconSetZIP.openInputStreamConnection(DownloadIconSetZIP.java:73)
    at com.linkezzi.web.DownloadIconSetZIP.doInBackground(DownloadIconSetZIP.java:45)
    at android.os.AsyncTask$2.call(AsyncTask.java:185)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
    at java.lang.Thread.run(Thread.java:1019)

Код указан ниже.

public class DownloadIconSetZIP extends AsyncTask {

        private File root  = null;
        private String url = null;
        private File pathToLinkEziiIconSetRootFolder = null;
        private File toBeExtracted = null;
        private FileOutputStream fOut  = null;
        private Context mContext = null;
        private InputStream input  = null;


        public DownloadIconSetZIP(Context mContext,String uriZIP){

            this.url = uriZIP;
            this.mContext = mContext;
        }
        protected Object doInBackground(Object[] params) {

            if(this.url != null){

                root = Environment.getExternalStorageDirectory();

                try {

                    Log.e("Downloading Iconset in BackGround","URl = "+ url);

                    openInputStreamConnection();

                    Log.e("Iconset is Downloading from the URI  = ",url.toUpperCase());

                    pathSetInLocalFileSystem();

                    downloadFile(input);


                }catch(MalformedURLException malformedURLException){

                    malformedURLException.printStackTrace();

                }catch (Exception e) {

                    e.printStackTrace();

                }

            }

            return null;
        }
        private void openInputStreamConnection() throws IOException,
                MalformedURLException {


            try {
                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
//              conn.setDoInput(true);
                conn.setConnectTimeout(30000); // timeout 10 secs
                conn.connect();
                input = conn.getInputStream();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }

        }
        private void downloadFile(InputStream input) throws IOException {
            int byteCount = 0;
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = input.read(buffer)) != -1) {

                fOut.write(buffer, 0, bytesRead);
                byteCount += bytesRead;

            }
            fOut.flush();
            fOut.close();
        }

        private void pathSetInLocalFileSystem() throws FileNotFoundException {


            pathToLinkEziiIconSetRootFolder = searchFileInThisDirectory(root);

            if(pathToLinkEziiIconSetRootFolder == null){
                pathToLinkEziiIconSetRootFolder = new File(root.getAbsolutePath(),"LinkEziiIconsets");

                if(!pathToLinkEziiIconSetRootFolder.exists() && pathToLinkEziiIconSetRootFolder.mkdir()){
                    Log.e("LinkEzii Iconset Container Folder is Created","LinkEzii Iconset Container Folder is Created");
                }else{
                    Log.e("LinkEzii Iconset Container is Not Created","LinkEzii Iconset Container is Not Created");
                }
            }

            File downloadedIconSetFile = new File(pathToLinkEziiIconSetRootFolder.getAbsolutePath(),"IconSetName Comes Here...");

            if(!downloadedIconSetFile.exists()){
                downloadedIconSetFile.mkdir();
                Log.e("Container is Created for Iconset","Container is Created for iconset");
            }


            if(downloadedIconSetFile!=null){
                toBeExtracted = new File(downloadedIconSetFile, "IconSet Zip Format.zip");
                fOut = new FileOutputStream(toBeExtracted);
            }

        }
        private File searchFileInThisDirectory(File file) throws NullPointerException {

            if(file == null){
                throw new NullPointerException();
            }

            File[] listFiles = file.listFiles();

            File pathToLinkEziiIconSetRootFolder = null;

            for(File searchIT: listFiles){
                if(file.isDirectory() && file.getName().equals("LinkEziiIconsets")){
                    pathToLinkEziiIconSetRootFolder = file;

                    return pathToLinkEziiIconSetRootFolder;
                }
            }

            return pathToLinkEziiIconSetRootFolder;

        }

        protected void onCancelled() {
            super.onCancelled();
            Log.i("Downloading is Cancelled","Download is Cancelled");
        }

        protected void onPostExecute(Object result) {
                super.onPostExecute(result);

//          Decompressing the File
            if(toBeExtracted != null){

//              Just to Move the Decompressing  to the Back Ground Thread
                new Thread(new Runnable() {

                    @Override
                    public void run() {

                        DecompressDownloadedDiagram decompressdDownloadedDiagram = new DecompressDownloadedDiagram(toBeExtracted.getPath(), toBeExtracted.getPath(),toBeExtracted);
                        decompressdDownloadedDiagram.unzip();
                        toBeExtracted.delete();
                    }
                }).start();

             Toast.makeText(mContext, "Icons Set is Successfully Downloaded", Toast.LENGTH_LONG).show();

            }else{
                Toast.makeText(mContext, "Error! while downloading diagram", Toast.LENGTH_LONG).show();
                Log.e("Some Error Occure While Downloading Diagram","Some Error Occure While Downloading Diagram");
            }

            Log.i("Downloading is Successful","Downloading is Successful");
        }

        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("Downloading is Starting","Downloading is Starting");
        }

        protected void onProgressUpdate(Object[] values) {
            super.onProgressUpdate(values);

            Log.i("Downlaoding is in Progress","Downloading is in Progress");
        }


    }

1 Ответ

3 голосов
/ 15 декабря 2011

MalformedURLException обычно выдается, когда к системе не подключен протокол, вы должны проверить, является ли какой-либо протокол таким, проверяя, присутствует ли :// в вашей строке URL-адреса. Если ваш URL имеет www, вы можете проверить его с целым http://.

Найдите вхождение http://, вызвав метод contains() в строке url. Если вы можете найти, проверьте, являются ли они начальными символами строкового вызова url.startsWith("http://"), чтобы убедиться, что это исключение не может быть выдано.

Если ни один из вышеуказанных тестов не пройден, просто добавьте эту строку.

url = "http://"+url;

...