2014-09-23 1 views
1
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합니다.파일 이름에 공백이 포함 된 경우 어떻게 안드로이드에 URLConnection과 함께 다운로드 할 수 있습니까?

다운로드 URL에 대한 라이브러리 또는 다른 알고리즘이 있습니까?

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

답변

0

당신은 URL의 당신의 파일 이름 부분을 인코딩해야합니다 같은 것을 할 코드에서

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

:

+0

정말 대단합니다. 시도해 보겠습니다. 감사합니다. – massaimara98

+0

감사합니다. 덕분에 시험을 보았습니다. 계속 작업 할 수 있습니다. – massaimara98

+0

정확하지 않습니다. 그것의 이름에도 불구하고,'URLEncoder'는'% 20'에 대한 조정 후 여기에서 알 수 있듯이, URL이 아닌 인수 이름과 값을 인코딩하기위한 것입니다. 올바른 기술은 @ PeterPeiGuo의 답변에 나와 있습니다. – EJP

3

당신은 URL을 탈출하고 다음처럼해야 :

String encodedFilename = URLEncoder.encode(filename, "UTF-8").replace("+", "%20"); 
URL url = new URL("http://www.exampleserver.com/" + encodedFilename); 
+0

공간을 볼 때 "% 20"으로 변환 하시겠습니까? – massaimara98

+1

네,하지만 그보다 더 많은 규칙이 있습니다. 따라서 위에 나온 코드를 사용하는 것이 가장 좋습니다. 이는 당신을 위해하는 것입니다 - 답변을 업데이트했습니다. –

관련 문제