我一直在应用这个异常的简单解决方案。我在清单中应用了权限,也使用了实际的设备,而不是模拟器。
这是:
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" />
答案 0 :(得分:1)
问题是由于此行导致的无效网址引起的
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);
它会尝试找到最后一个斜线,并且&#34;拆分&#34;相应的URL。