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

Java 如果文件名包含空格,我们如何在android中使用URLConnection下载?,java,android,Java,Android,我正在使用此算法,但如果文件名包含空格,则得到java.io.FileNotFoundException和getResponseCode:400 下载URL是否有库或不同的算法?您需要转义URL,并使其如下所示: try { int count; URL url = new URL("http://www.exampleserver.com/file names.txt"); URLConnection connection = url.openConnection();

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


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

您需要转义URL,并使其如下所示:

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();
}
在代码中执行以下操作:

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

您需要转义url,并使其如下所示:

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();
}
在代码中执行以下操作:

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

您需要对URL的文件名部分进行编码:

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

您需要对URL的文件名部分进行编码:

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

你的意思是当我看到空格时,转换成“%20”?是的,但规则不止这些,所以最好是使用我上面的代码,这对你来说很有用-我更新了答案。你的意思是当我看到空格时,转换成“%20”?是的,但规则不止这些,所以最好是使用我上面的代码,我更新了答案。多亏了你,我试过了。我可以继续我的工作。这是不正确的。尽管名称不同,
urlcoder
用于编码参数名称和值,而不是URL,正如您可以从这里的
%20
的工作地点差价调整数中看出的那样。@PeterPeiGuo的回答给出了正确的技巧。多亏了你,我试过了。我可以继续我的工作。这是不正确的。尽管名称不同,
urlcoder
用于编码参数名称和值,而不是URL,正如您可以从这里的
%20
的工作地点差价调整数中看出的那样。@PeterPeiGuo的回答给出了正确的技巧。