Android获取网络时间的方法

1、经过免费或者收费的API接口获取

一、免费
  • QQ:http://cgi.im.qq.com/cgi-bin/cgi_svrtime
  • 淘宝:http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp
  • 苏宁:http://quan.suning.com/getSysTime.do
二、收费

详情:标准北京时间php

2、经过访问某个地址并获取时间

一、HTTP协议访问某个网站

原理:HTTP协议的响应体中带有时间html

HTTP/1.1 200 OK
Bdpagetype: 1
Bdqid: 0xf15515780000825e
Cache-Control: private
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html
Cxy_all: baidu+d96801e638778b0ae9d58b4082cb757e
Date: Fri, 29 Jun 2018 06:08:38 GMT
Expires: Fri, 29 Jun 2018 06:08:00 GMT

Android 获取方式:java

private void getNetTime() {
        URL url = null;//取得资源对象
        try {
            url = new URL("http://www.baidu.com");
            //url = new URL("http://www.ntsc.ac.cn");//中国科学院国家授时中心
            //url = new URL("http://www.bjtime.cn");
            URLConnection uc = url.openConnection();//生成链接对象
            uc.connect(); //发出链接
            long ld = uc.getDate(); //取得网站日期时间
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(ld);
            final String format = formatter.format(calendar.getTime());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "当前网络时间为: \n" + format, Toast.LENGTH_SHORT).show();
                    tvNetTime.setText("当前网络时间为: \n" + format);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
}

详情:Android - 获取系统时间和网络时间api

二、NTP客户端访问NTP服务器

NTP(Network Time Protocol)是用来使计算机时间同步化的一种协议,它能够使计算机对其服务器或时钟源(如石英钟,GPS等等)作同步化,它能够提供高精准度的时间校订(LAN上与标准间差小于1毫秒,WAN上几十毫秒),且可介由加密确认的方式来防止恶毒的协议攻击。服务器

// NTP server list: http://tf.nist.gov/tf-cgi/servers.cgi
// NTP server list: http://www.ntp.org.cn/pool.php
public static final String TIME_SERVER = "time-a.nist.gov";

public static long getCurrentNetworkTime() {
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    //long localDeviceTime = timeInfo.getReturnTime();  
    long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();   

    Date time = new Date(serverTime);
    Log.d(TAG, "Time from " + TIME_SERVER + ": " + time);

    return serverTime;
}

详情:Get Network Time网络

相关文章
相关标签/搜索