1

I am trying to make this function download file from the internet. I pass two arguments to it: from - url to file on the net, to - local file path; The problem it throws IOException when opening stream:

Authority expected at index 7: http://

Here is my code:

private boolean downloadFile(String pathFrom, String pathTo)
{
    URL url;
    ReadableByteChannel rbc;
    FileOutputStream fos;

    try {
        url = new URL(pathFrom);
        rbc = Channels.newChannel(url.openStream());
        fos = new FileOutputStream(pathTo);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        return true;
    } catch (MalformedURLException e) {
        Log.e(TAG, "Failed to download file (" + pathFrom + ") because of malformed URL.");
    } catch (FileNotFoundException e) {
        Log.e(TAG, "Failed to download file (" + pathFrom + ") because FileNotFoundException occured when opening output stream: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "Failed to download file (" + pathFrom + ") because IOException occured when transfering file or opening input stream: " + e.getMessage());
    }

    return false;
}

As you can see, it also prints url of the file and it's just fine. You can paste it in the browser and it opens the file.

Anyone knows what causes it and/or how to fix it?

P.S. I have both uses permissions - INTERNET and WRITE_EXTERNAL_STORAGE

1 Answer 1

3

Try to encode your url with the use of URLEncoder, in the UTF-8 format.

Sample code:

String encodedUrl = URLEncoder.encode(url.toString(), "UTF-8"); 
Sign up to request clarification or add additional context in comments.

3 Comments

It messes up my URL (replaces slashes with %2F and ':' with %3A) and causes malwared url exception.
Hm, without further more information, what is your character at index 7? It is probably something with the URL itself, I think.
You are right. I was reading logs again and again and found that at some point http://... changes into http:/... :| It's caused by File.getParent() (used to remove the filename from URL). Must find a new function for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.