Search code examples
javaandroidurlconnection

URLConnection time out issue


I am working in an android application and I am downloading a file from an url. Every thing works fine, but when the internet connection goes in between(After opening a connection) the downloading time out never occurs and the connection never ends.

Suggest me a solution to solve this issue

        **URL url = new URL("fileURL");
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        File file = new File(context.getFilesDir(), "" + filename);
        // getting file length
        int lenghtOfFile = connection.getContentLength();
        // input stream to read file - with 8k buffer
        InputStream input = new BufferedInputStream(url.openStream(), 8192);
        // Output stream to write file
        OutputStream output = new FileOutputStream(file);
        byte data[] = new byte[1024];
        long total = 0;
        while ((count = input.read(data)) != -1) {
            total += count;
            int status = (int) ((total * 100) / lenghtOfFile);
            publishProgress("" + status);
            // writing data to file
            output.write(data, 0, count);
        }
        // flushing output
        output.flush();
        // closing streams
        output.close();
        input.close()**

Solution

  • You can use Retrofit Library to download files from server,

    Retrofit uses OkHttp internally

    Please refer below URL,

    https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server

    final FileDownloadService downloadService =
                ServiceGenerator.createService(FileDownloadService.class);
    
        Call<ResponseBody> call =
                downloadService.downloadFileWithDynamicUrlSync(fileUrl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody>
                    response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "server contacted and has file");
    
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            boolean writtenToDisk = writeResponseBodyToDisk(FileDownloadActivity.this, response.body(), null);
    
                            Log.d(TAG, "file download was a success? " + writtenToDisk);
                            return null;
                        }
                    }.execute();
                } else {
                    Log.d(TAG, "server contact failed");
                }
            }
    

    And you can also use @Streaming annotation for large files. Retrofit will handle the large file download also