Search code examples
androidexceptionandroid-manifesturlconnectionunknown-host

UnknownHostException when downloading file


I've been applying what seems to be simple solutions for this exception. I applied permissions in manifest and also use actual device and not an emulator.

This is :

    fileUrl = "http://xxx.xxx.xx.xx/resources/upload/pdfs/sample ははは.pdf";
    String urlLastPath = fileUrl.replaceFirst(".*/([^/?]+).*", "$1"); //urlLastPath = sample ははは.pdf

    String urlEncoded = URLEncoder.encode(urlLastPath, "utf-8"); //urlEncoded = sample %E3%81%AF%E3%81%AF%E3%81%AF.pdf

    File file = new File(fileUrl);
    String fileUrlRemains = file.getPath().replaceAll(file.getName(), ""); //fileUrlRemains = http://xxx.xxx.xx.xx/resources/upload/pdfs/

    String urlDecoded = null;
    if (urlEncoded.contains(" ")) {
        urlDecoded = urlEncoded.replaceAll(" ", "%20");
        urlStr = fileUrlRemains + urlDecoded;
    } else if (urlEncoded.contains("+")) {
        urlDecoded = urlEncoded.replaceAll(Pattern.quote("+"), "%20");
        urlStr = fileUrlRemains + urlDecoded;
    } else {
        urlStr = fileUrlRemains + urlEncoded;
    }

    URL url = new URL(urlStr); //urlStr is the complete file url(http://xxx.xxx.xx.xx/resources/upload/pdfs/sample%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf)

    URLConnection conection = url.openConnection();
    conection.connect(); //This is where the exception points

    .
    .
    .

My manifest:

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Solution

  • The problem is caused by invalid URL due to this line

    String fileUrlRemains = file.getPath().replaceAll(file.getName(), "");
    //expected: http://xxx.xxx.xx.xx/resources/upload/pdfs/
    //actually: http:\xxx.xxx.xx.xx\resources\upload\pdfs\
    

    Note the single slash caused by converting a URL to File.

    I'm not sure what the RegEx does in the beginning, but here is a simpler approach to get both filename and the rest of the URL.

    int i = fileUrl.lastIndexOf("/") + 1;
    String urlLastPath = fileUrl.substring(i, fileUrl.length());
    String fileUrlRemains = fileUrl.substring(0, i);
    

    It will try to find the last slash, and "split" the URL accordingly.