我有一个代理微服务,它从API读取并返回一些过滤后的输出。我正在使用HttpsURLConnection(使用URLConnection中的方法)。
String httpsURL = "https://myrestserver/path"+ id ;
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy", 8080));
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection(proxy);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type","application/json");
con.setRequestProperty("Authorization", authString);
con.setDoInput(true);
DataInputStream input = new DataInputStream( con.getInputStream() );
result = new Scanner(input).useDelimiter("\\Z").next();
我想使用缓存来减少流量和延迟,但我想每小时更新一次。
我的问题是:如何使用URLConnection
每小时刷新一次缓存?
假设 - Java 7.
答案 0 :(得分:0)
据我所知,您需要以固定的间隔呼叫重复客户端。这是一种方法(Java7)。不确定这是否符合您的需求。这里,在虚拟URL上每2秒进行一次服务调用。由于任务一次又一次地调用,数据将被刷新(输入数据流将基于从服务器返回的数据)
import java.io.DataInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class CallAPIProxy {
Timer timer;
public CallAPIProxy(int seconds) {
timer = new Timer();
// timer.schedule(new APICallerTask(), seconds * 1000);
timer.scheduleAtFixedRate(new APICallerTask(), 2000, 2000);
}
class APICallerTask extends TimerTask {
public void run() {
String httpsURL = "http://jsonplaceholder.typicode.com/posts/1";
// String httpsURL = "https://myrestserver/path" + id;
// Proxy proxy = new Proxy(Proxy.Type.HTTP, new
// InetSocketAddress("myproxy", 8080));
URL myurl;
try {
myurl = new URL(httpsURL);
System.setProperty("http.agent", "Chrome");
// HttpsURLConnection con = (HttpsURLConnection)
// myurl.openConnection(proxy);
HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("GET");
// con.setRequestProperty("Content-Type", "application/json");
// con.setRequestProperty("Authorization", authString);
con.setDoInput(true);
DataInputStream input = new DataInputStream(con.getInputStream());
// String result = new
// Scanner(input).useDelimiter("\\Z").next();
// Scanner result = new Scanner(input);
StringBuffer inputLine = new StringBuffer();
String tmp;
while ((tmp = input.readLine()) != null) {
inputLine.append(tmp);
System.out.println(tmp);
}
input.close();
System.out.println("Result " + inputLine);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
System.out.println("About to call the API task.");
new CallAPIProxy(2);
System.out.println("Task scheduled.");
}