2009-09-15 2 views
1

제목을 통해 말하듯이 HTTP를 통해 파일을 다운로드하고 그 내용을 String에 저장하려고합니다. 따라서 내 접근 방식은 다음과 같습니다.HTTP를 통해 파일을 다운로드하고 해당 내용을 Java String의 문자열에 저장하는 방법

URL u = new URL("http://url/file.txt"); 

ByteArrayBuffer baf = new ByteArrayBuffer(32); 
InputStream in = (InputStream) u.getContent(); 
BufferedInputStream bis = new BufferedInputStream(in); 

int buffer; 
while((buffer = bis.read()) != -1){ 
    baf.append((byte)buffer); 
} 

bis.close(); 
in.close(); 

스트림에서 읽으려고하면 코드가 실패하고 스트림이 닫힌다는 것을보고합니다.

이제 브라우저를 통해 파일에 액세스하려고하면 다운로드 할 파일이 아닌 텍스트로 제공됩니다.

나는이 웹을 어디서도 검색하지 못했기 때문에 약간의 통찰력이 많이 들었을 것입니다!

감사합니다.

답변

2

Apache Commons의 HttpClient을 확인하십시오. 특히 getResponseBodyAsString() 방법을 참조하십시오.

+0

내가 실제로 사용 reponse.getEntity()의 getContent()하고 매력 또한 – alkar

+0

처럼 작동 당신이 예를 여기에서 볼 수 있습니다. http://www.mkyong.com/java/apache-httpclient-examples/ –

3

다음은이 작업을 수행하는 코드입니다. 현재 시도하고있는 것 외에도 GZip 압축 (헤더에 Accept-Encoding: gzip, deflate으로 설정 한 경우)을 처리 할 수 ​​있으며 자동으로 인코딩을 감지합니다 (문자열 처리에 필요함).

private InputStream prepareInputStream(String urlToRetrieve) throws IOException 
{ 
    URL url = new URL(urlToRetrieve); 
    URLConnection uc = url.openConnection(); 
    if (timeOut > 0) 
    { 
     uc.setConnectTimeout(timeOut); 
     uc.setReadTimeout(timeOut); 
    } 
    InputStream is = uc.getInputStream(); 
    // deflate, if necesarily 
    if ("gzip".equals(uc.getContentEncoding())) 
     is = new GZIPInputStream(is); 

    this.lastURLConnection = uc; 
    return is; 
} 
// detects encoding associated to the current URL connection, taking into account the default encoding 
public String detectEncoding() 
{ 
    if (forceDefaultEncoding) 
     return defaultEncoding; 
    String detectedEncoding = detectEncodingFromContentTypeHTTPHeader(lastURLConnection.getContentType()); 
    if (detectedEncoding == null) 
     return defaultEncoding; 

    return detectedEncoding; 
} 


public static String detectEncodingFromContentTypeHTTPHeader(String contentType) 
{ 
    if (contentType != null) 
    { 
     int chsIndex = contentType.indexOf("charset="); 
     if (chsIndex != -1) 
     { 
      String enc = StringTools.substringAfter(contentType , "charset="); 
      if(enc.indexOf(';') != -1) 
       enc = StringTools.substringBefore(enc , ";"); 
      return enc.trim(); 
     } 
    } 
    return null; 
} 


// retrieves into an String object 
public String retrieve(String urlToRetrieve) 
throws MalformedURLException , IOException 
{ 
    InputStream is = prepareInputStream(urlToRetrieve); 
    String encoding = detectEncoding(); 
    BufferedReader in = new BufferedReader(new InputStreamReader(is , encoding)); 
    StringBuilder output = new StringBuilder(BUFFER_LEN_STRING); 
    String str; 
    boolean first = true; 
    while ((str = in.readLine()) != null) 
    { 
     if (!first) 
      output.append("\n"); 
     first = false; 
     output.append(str); 
    } 
    in.close(); 
    return output.toString(); 
} 

코드는 Phramer project에서 info.olteanu.utils.retrieve.RetrievePage입니다.

+0

gzip 부분에 대해 감사드립니다. – Karussell

3

이 코드를 사용해보십시오. 테스트하지 않았으므로 컴파일되지 않았을 수 있지만 모든 가능한 예외가 잡히지는 않았지만 쉽게 추가 할 수 있습니다. 제한 시간에주의하십시오. 자원을 사용할 수없는 경우 나중에 프로그램이 중단 될 수 있으므로 무한대 시간 초과를 사용하지 마십시오. 간단한 텍스트 파일 검색 이상의 것을하고 있다면 Apache Commons의 HTTPClient을 살펴볼 수 있습니다.

URL url = new URL("http://mydomain.com/file.txt"); 
    URLConnection urlConnection = url.openConnection(); 
    urlConnection.setConnectTimeout(1000); 
    urlConnection.setReadTimeout(1000); 
    BufferedReader breader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 

    StringBuilder stringBuilder = new StringBuilder(); 

    String line; 
    while((line = breader.readLine()) != null) { 
     stringBuilder.append(line); 
    } 

    System.out.println(stringBuilder.toString()); 
+0

오, Charsets에 대한 처리가 없습니다. 그러나이 코드는 시작점을 제공해야합니다. – Malax

+0

나는 이것을 이미 시도했지만 null 문자열을 읽는다. HTTPClient를 확인하겠습니다. – alkar