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
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");
来源:https://stackoverflow.com/questions/7066460/javaandroid-ioexception-authority-expected-at-index-7-http