用java代码获取baidu官方时间

这段Java代码演示了如何从百度获取官方时间。通过创建URL对象,打开连接,读取响应并解析其中的时间字符串,将毫秒转换为日期对象进行显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;



public class TT {
public static void main(String[] args) {
	try {
		URL url = new URL("http://open.baidu.com/special/time/");
//		System.out.println(url.getHost());
//		System.out.println(url.getFile());
//		System.out.println(url.getProtocol());
		try {
			InputStream fis= url.openStream();
			InputStreamReader isr = new InputStreamReader(fis,"GBK");
			BufferedReader bf = new BufferedReader(isr);
			String s=null;
			StringBuilder sb = new StringBuilder();
			while((s=bf.readLine())!=null){	
				sb.append(s);//之所以加个StringBuilder是为了方便后面截取时间字符串
				System.out.println(s);
			}
//			System.out.println(sb);
//			System.out.println(sb.indexOf("window.baidu_time("));
			Long time=Long.valueOf(sb.substring(sb.indexOf("window.baidu_time(")+"window.baidu_time(".length(), sb.indexOf("window.baidu_time(")+"window.baidu_time(".length()+13));//浏览器打开上面的URL,右键查看源代码,找到13位的毫秒Long类型数据,这就是我们要的时间
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(time);
			System.out.println(c.getTime());//通过简单的时间处理来输出较为直观的时间格式
			bf.close();
			isr.close();
			fis.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值