利用正则解析国家授时中心页面上的时间
对于程序开发来说,尤其是游戏程序开发,光光客户端的时间系统是满足不了需求的。下面利用正则解析国家授时中心网络服务器:
国家授时中心网络服务器网址为:http://www.time.ac.cn/stime.asp 。
代码如下:
/** * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStram 4.从InputStream当中读取数据 * @author long * @param urlStr * @return */public static String download(String urlStr) {StringBuffer sb = new StringBuffer();String line = null;BufferedReader buffer = null;try {// 创建一个URL对象URL url = new URL(urlStr);// 创建一个Http连接HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// 使用IO流读取数据buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));while ((line = buffer.readLine()) != null) {sb.append(line);}} catch (Exception e) {e.printStackTrace();} finally {try {buffer.close();} catch (Exception e) {e.printStackTrace();}}return sb.toString();}这里没有截取年月日,但是道理一样。