2009-07-27 2 views
0

URLConnection 클래스를 사용하고 있습니다. URL을 사용할 수 없더라도 지정된 URL로 스트림을 가져올 수 있기를 원합니다. 일부 로컬 파일 시스템 디렉토리에 대한 URL의 내용) - 이제이 코드를 몇 번 작성 했으므로 (이 파일에 만족할 수 없음)이 작업을 수행 할 수있는 더 좋은 것이 있는지 궁금해하고있었습니다.URLConnection 주위에 일부 로컬 캐시를 래핑하는 방법이 있습니까?

답변

-1

방금이 문제가 발생하여 내 웹 캐시 클래스를 던졌습니다. 아직 테스트하지 않았지만 원하는 경우 시도해 볼 수 있습니다. 페이지를 캐싱 할 디렉토리로 구성한 다음 getPage (String url)를 호출하여 페이지를 가져 오십시오. getPage는 먼저 캐시 디렉토리를 확인한 다음 캐시 디렉토리가없는 경우이를 캐시로 다운로드하고 결과를 리턴합니다. 캐시 파일 이름은 url.hashCode() + ".cache"

입니다. 이는 페이지의 소스를 가져 오는 것일 뿐이므로 URLConnection을 사용하여 수행 할 작업이 무엇인지 모르겠지만, 도움.

/** 
* A tool for downloading and reading the source code of HTML pages. 
* Prevents repeated downloading of pages by storing each page in a cache. 
* When it recieves a page request, it first looks in its cache. 
* If it does not have the page cached, it will download it. 
* 
* Pages are stored as <cachedir>/<hashcode>.cache 
* 
* @author Mike Turley 
*/ 

import java.io.*; 
import java.net.*; 

public class WebCache { 
    File cachedir; 
    boolean enabled; 

    /** 
    * Create a web cache in the given directory. 
    */ 
    public WebCache(File cachedir, boolean enabled) { 
     this.cachedir = cachedir; 
     this.enabled = enabled; 
    } 
    public WebCache(String cachedir, boolean enabled) { 
     this.cachedir = new File(cachedir); 
     this.enabled = enabled; 
    } 
    public WebCache(File cachedir) { 
     this.cachedir = cachedir; 
     this.enabled = true; 
    } 
    public WebCache(String cachedir) { 
     this.cachedir = new File(cachedir); 
     this.enabled = true; 
    } 

    /** 
    * Get the content for the given URL. 
    * First check the cache, then check the internet. 
    */ 
    public String getPage(String url) { 
     try { 
      if(enabled) { 
       File cachefile = new File(cachedir.getAbsolutePath() + url.hashCode() + ".cache"); 
       //FIXME - might be missing a slash between path and hashcode. 
       if(cachefile.exists()) return loadCachedPage(url); 
      } 
      return downloadPage(url); 
     } catch(Exception e) { 
      System.err.println("Problem getting page at " + url); 
      e.printStackTrace(); 
      return null; 
     } 
    } 

    public void clear() { 
     try { 
      File[] cachefiles = cachedir.listFiles(); 
      for(int i=0; i<cachefiles.length; i++) { 
       cachefiles[i].delete(); 
      } 
      cachedir.delete(); 
     } catch(Exception e) { 
      System.err.println("Problem clearing the cache!"); 
      e.printStackTrace(); 
     } 
    } 

    public String downloadPage(String url) { 
     try { 
      URL weburl = new URL(url); 
      URLConnection urlc = weburl.openConnection(); 
      urlc.setDoInput(true); 
      urlc.setDoOutput(false); 
      BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); 
      if(!cachedir.exists()) cachedir.mkdir(); 
      File outfile = new File(cachedir.getAbsolutePath() + url.hashCode() + ".cache"); 
      // FIXME - might be missing a slash between path and hashcode. 
      PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); 
      StringBuilder sb = new StringBuilder(""); 
      String inputline; 
      while ((inputline = in.readLine()) != null) { 
       out.println(inputline); 
       sb.append(inputline); 
      } 
      in.close(); 
      out.close(); 
      return sb.toString(); 
     } catch(Exception e) { 
      System.err.println("Problem connecting to URL " + url); 
      e.printStackTrace(); 
      return null; 
     } 
    } 

    public String loadCachedPage(String url) { 
     try { 
      File infile = new File(cachedir.getAbsolutePath() + url.hashCode() + ".cache"); 
      // FIXME - might be missing a slash between path and hashcode. 
      BufferedReader in = new BufferedReader(new FileReader(infile)); 
      StringBuilder sb = new StringBuilder(""); 
      while (in.ready()) sb.append(in.readLine()); 
      in.close(); 
      return sb.toString(); 
     } catch(Exception e) { 
      System.err.println("Problem loading cached page " + url); 
      e.printStackTrace(); 
      return null; 
     } 
    } 

    public void setEnabled(boolean enabled) { 
     this.enabled = enabled; 
    } 
} 
+0

이 사양은 HTTP 사양이 리소스를 캐시 할 수있는시기와 방법 및 캐싱하지 않아야하는시기를 자세히 설명하지 않는다는 점을 지적하고자합니다. 3xx 재발급, 5xx 서버 오류, 유효성 검사 (E-Tag, Last-Modified), 비 손해가 아닌 방법 (POST/PUT/DELETE) 등과 같은 상태 코드 처리가 누락되었습니다. 문제의 큰 더미 ... 이처럼 장애가있는 캐싱 레이어를 사용하기 전에 squid, ngnix 등과 같은 독립형 프록시 설정을 사용하는 것이 좋습니다. – ordnungswidrig

-1

하지 마십시오. 캐싱 HTTP 프록시를 배포합니다. 아파치 오징어 예를 들어.

1

URLConnection에서 Apache HttpClient로 전환 한 경우 HttpClient Cache을 사용할 수 있습니다.

관련 문제