0

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

这是 :

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

1 回答 1

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\

请注意将 a 转换URLFile.

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

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

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

于 2014-09-04T09:56:06.020 回答