Java(Android) IOException: Authority expected at index 7: http://

时间秒杀一切 提交于 2019-11-30 20:53:56

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!