Created
June 2, 2014 19:35
-
-
Save loriopatrick/8f8488047ebae22ab9fb to your computer and use it in GitHub Desktop.
A simple method to cache web requests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.URL; | |
import java.net.URLEncoder; | |
/** | |
* @author Patrick Lorio | |
*/ | |
public class WebCache { | |
public static InputStream GetWeb(String url) throws IOException { | |
File file = new File("cache/" + URLEncoder.encode(url, "UTF-8")); | |
if (file.exists()) { | |
return new FileInputStream(file); | |
} | |
OutputStream cacheStream = new FileOutputStream(file); | |
InputStream webStream = new URL(url).openStream(); | |
return new InputStream() { | |
@Override | |
public int read() throws IOException { | |
int value = webStream.read(); | |
cacheStream.write(value); | |
return value; | |
} | |
@Override | |
public void close() throws IOException { | |
super.close(); | |
cacheStream.close(); | |
webStream.close(); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment