一开始采取的方案是,使用命令行调用curl -o(这个方案搜“java curl”应该就能找到具体实现了),然后对文件进行字符串解析。
但这个方法会访问磁盘,其实完全没有必要。
为了避免句柄不够用而抛出java.net.SocketException: Too many open files,可以使用closeableHttpClient,在用完后主动关闭。
但频繁new/close会影响性能,所以可以使用连接池(下文没有使用)。
public class MyClass {
private String yourURL;
private int yourTimerInterval;
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet(yourURL);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String message = EntityUtils.toString(entity, "utf-8");
String[] lines = message.split("\n");
for(String line : lines) {
//你的字符串处理逻辑
}
} else {
//你的连接失败提示
}
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
//你的异常处理
} catch (ParseException e) {
//你的异常处理
} catch (IOException e) {
//你的异常处理
} finally {
try {
httpclient.close();
} catch (IOException e) {
//你的异常处理
}
}
public void startDoSomething() {
Timer timer = new Timer();
timer.schedule(new TImerTask() {
@Override
public void run() {
get();
}
}, 0, yourTimerInterval);
//第二个参数表示多久后开始第一次定时(本文为0)。
//第三个参数表示每隔多久执行一次(本文为yourTImerInterval)。
//两者的单位均为毫秒。
}
public static void main(String[] args) {
MyClass myclass = new MyClass();
myclass.startDoSomething();
}
}