URLConnection 클래스를 사용하고 있습니다. URL을 사용할 수 없더라도 지정된 URL로 스트림을 가져올 수 있기를 원합니다. 일부 로컬 파일 시스템 디렉토리에 대한 URL의 내용) - 이제이 코드를 몇 번 작성 했으므로 (이 파일에 만족할 수 없음)이 작업을 수행 할 수있는 더 좋은 것이 있는지 궁금해하고있었습니다.URLConnection 주위에 일부 로컬 캐시를 래핑하는 방법이 있습니까?
0
A
답변
-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;
}
}
-1
하지 마십시오. 캐싱 HTTP 프록시를 배포합니다. 아파치 오징어 예를 들어.
1
URLConnection
에서 Apache HttpClient로 전환 한 경우 HttpClient Cache을 사용할 수 있습니다.
관련 문제
- 1. make : 명령 셸 섹션을 래핑하는 방법이 있습니까?
- 2. Java URLConnection
- 3. MvcSiteMap에서 캐시를 무효화하거나 새로 고치는 방법이 있습니까
- 4. Html.BeginForm에서 일부 HTML을 래핑하는 조건부 논리
- 5. 다른 사용자와 URLConnection
- 6. 'using'블록이있는 서비스에서 모든 WCF 메서드를 래핑하는 더 쉬운 방법이 있습니까?
- 7. 쉘 스크립트의 하위 디렉터리 아래에있는 임의의 명령을 래핑하는 방법이 있습니까
- 8. Websphere slow URLConnection
- 9. git의 기록에서 일부 파일을 제거하는 방법이 있습니까?
- 10. 특정 날짜 이전에서 캐시를 무시하도록 브라우저를 알 수있는 방법이 있습니까?
- 11. 애플릿이 프로그래밍 방식으로 자체 캐시를 비울 수있는 방법이 있습니까?
- 12. 로컬 호스트에 IntenseDebate를 설치하는 방법이 있습니까?
- 13. ftp에서 로컬 디렉토리의 내용을 나열하는 방법이 있습니까?
- 14. 로컬 메이븐 저장소를 비활성화하는 방법이 있습니까?
- 15. URLConnection 대리인 메서드가 호출되지 않습니다.
- 16. Webview 예제가 주위에 회전 있습니까?
- 17. 이미지 주위에 텍스트를 둘러싸는 방법은 무엇입니까?
- 18. webstart에서 Java 다운로드 캐시를 사용하는 방법은 무엇입니까?
- 19. Gradle에서 로컬 ivy 저장소의 캐시를 무시하는 방법은 무엇입니까?
- 20. 클래스 주위에 래퍼를 자동으로 생성하는 도구가 있습니까?
- 21. 일부 Mathematica 그래프 주위에 흰 여백을 제거하는 방법
- 22. 웹 서비스에서 캐시를 사용할 수 있습니까?
- 23. jQuery 테이블 셀을 래핑하는 방법
- 24. COM을 사용하지 않고 도메인의 일부 사용자의 전자 메일을받을 방법이 있습니까?
- 25. jQuery에서 관리하지 않는 일부 HTML 컨텐트를 지정하는 방법이 있습니까?
- 26. 일부 조건이 충족 될 때까지 블록을 차단할 수있는 방법이 있습니까?
- 27. 일부 함수 나 연산자를 매개 변수로 전달하는 방법이 있습니까?
- 28. .NET MethodInfo 캐시를 지울 수 있습니까?
- 29. 왜`주위에 열을 넣으시겠습니까?
- 30. 중괄호로 숫자를 래핑하는 정규식?
이 사양은 HTTP 사양이 리소스를 캐시 할 수있는시기와 방법 및 캐싱하지 않아야하는시기를 자세히 설명하지 않는다는 점을 지적하고자합니다. 3xx 재발급, 5xx 서버 오류, 유효성 검사 (E-Tag, Last-Modified), 비 손해가 아닌 방법 (POST/PUT/DELETE) 등과 같은 상태 코드 처리가 누락되었습니다. 문제의 큰 더미 ... 이처럼 장애가있는 캐싱 레이어를 사용하기 전에 squid, ngnix 등과 같은 독립형 프록시 설정을 사용하는 것이 좋습니다. – ordnungswidrig