java - 如果文件名包含空格,我们如何在 Android 中使用 URLConnection 下载?

标签 java android

try {
    int count;
    URL url = new URL("http://www.exampleserver.com/file names.txt");
    URLConnection connection = url.openConnection();
    connection.setReadTimeout(TIMEOUT_CONNECTION);
    connection.setConnectTimeout(TIMEOUT_SOCKET);
    connection.setRequestProperty("connection", "close");
    connection.connect();
    int lengthOfFile = connection.getContentLength();
    long total = 0;
    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream(BasindaOneCikanDosyalar);
    byte data[] = new byte[40096];
    while ((count = input.read(data)) != -1) {
        total += count;
        output.write(data, 0, count);
    }
    output.flush();
    output.close();
    input.close();
} catch (IOException e1) {
    e1.printStackTrace();
}

我正在使用此算法,但如果文件名包含空格,我会得到 java.io.FileNotFoundExceptiongetResponseCode:400

是否有库或不同的下载 URL 算法?

最佳答案

您需要对 url 进行转义,并使其像下面这样:

http://www.exampleserver.com/file%20names.txt

在你的代码中做这样的事情:

URI uri = new URI("http", "www.exampleserver.com", "/file names.txt", null);
URL url = uri.toURL();

关于java - 如果文件名包含空格,我们如何在 Android 中使用 URLConnection 下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26006278/

相关文章:

java - 在 CardView android 上禁用按钮

java - 使用旧小程序中的deployjava.js 添加参数

java - 为什么只在顶级类或接口(interface)上枚举?

安卓 AAR NoClassDefFoundError

android - 如何在 Android 中使用带有 DiskLruCache 的 ContentProvider

java - 安卓开发 : Avoiding Internal Getters/Setters?

java - 如何在 Android 应用程序中查找某个地点的地址

android - 除了常规的 Activity 和 View 之外,ListActivity 和 ListView 还提供什么?

java - 使用 Junit 运行所有测试后如何获取多个测试类的测试结果

java - 卸载并再次安装应用程序时,Firebase 身份验证返回特定用户