【问题标题】:UnknownHostException when downloading file下载文件时出现UnknownHostException
【发布时间】:2014-09-04 07:08:48
【问题描述】:

我一直在为这个异常应用看似简单的解决方案。我在清单中应用了权限,并且还使用了实际设备而不是模拟器。

这是:

    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

    .
    .
    .

我的清单:

<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" />

【问题讨论】:

  • 不确定,但可能您应该对 URL 进行编码。见URL Encoding in Android
  • @AndrewT。我刚刚编辑了我的问题,实际上我已经对日语部分进行了编码。这之前有效,我不知道发生了什么。
  • 能否请您尝试从 Android 浏览器访问 URL(非编码和编码)?另外,也许从您的PC浏览器中检查它是否可以访问?
  • @AndrewT。我在两个平台都试过了,也编码和解码,URL下载成功。
  • 嗯,实际上当我尝试您的代码时,fileUrlRemains 变为“http:\xxx.xxx.xx.xx\resources\upload\pdfs\”(注意单斜杠,而不是双斜杠, http:\)

标签: android exception android-manifest urlconnection unknown-host


【解决方案1】:

问题是由于这一行导致的无效URL引起的

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\

注意将URL 转换为File 时产生的单斜线。

我不确定 RegEx 一开始是做什么的,但这里有一个更简单的方法来获取文件名和 URL 的其余部分。

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

它将尝试找到最后一个斜杠,并相应地“拆分” URL。

【讨论】:

    猜你喜欢
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多