Android 获取服务器网络时间

APP登录鉴权功能的数据上报涉及时间,获取本地时间可能错乱,需获取远程服务器时间。可使用互联网公司提供的时间API接口,如苏宁购物网站的时间地址。文章介绍了添加网络请求权限、编写网络请求类获取服务器网络数据及调用示例。

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

最近APP需要做一项登录鉴权的功能,涉及到数据上报。

数据上报就涉及到时间,如果时间不对,服务器可能会拒绝你的数据;就算不拒绝,你上报的数据也是不正确的,此时就会报错。(我的是 服务端返回错误码:415)

获取本地时间会因用户的设定而造成错乱,因此需要应用去获取远程服务器时间。如果你没有自己的服务器开展业务,也可以使用互联网公司提供的时间API接口。

我结合网上的各种案例,重新编写了一份逻辑。希望能对正在浏览本篇文章的你,提供一些帮助。

我这里直接访问的是苏宁购物网站的时间地址:http://quan.suning.com/getSysTime.do

可以看到接口提供的时间格式,如下:

{
  "sysTime2": "2019-04-19 10:23:04",
  "sysTime1": "20190419102304"
}

一. 添加网络请求权限

<uses-permission android:name="android.permission.INTERNET" />

二. 写一个网络请求的类,用于获取服务器网络数据

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HttpServerTime {
    private static final String TAG = "HttpServerTime";

    /**
     * 直接访问 http://quan.suning.com/getSysTime.do 可以看到接口提供的时间格式:
     *
     * {
     *   "sysTime2": "2019-04-19 10:23:04",
     *   "sysTime1": "20190419102304"
     * }
     *
     * 里面有两个时间数据 sysTime2 和 sysTime1,都是常见的时间格式,
     * 但我们在计算和存储都是以时间戳的形式,所以获取到时间后会对其进行转换。
     */

    public HttpServerTime() {

    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    public static final String getServerTimestamp() {
        final HttpServerTime httpServerTime = new HttpServerTime();
        final String jsonStr = httpServerTime.makeServiceCall("http://quan.suning.com/getSysTime.do");

        if (jsonStr != null) {
            try {
                final JSONObject json = new JSONObject(jsonStr);
                if (json.has("sysTime2")) {
                    final String date = json.getString("sysTime2");
                    return dateToTimestamp(date);
                }
            } catch (JSONException e) {
                // e.printStackTrace();
            }
        }

        // 未能获取远程时间,将获取本地时间,根据需要修改.
        return new Date().getTime() + "";
    }

    public static final String dateToTimestamp(String time) {
        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        final Date date;
        try {
            date = dateFormat.parse(time);
        } catch (ParseException e) {
            return "0";
        }

        return date.getTime() + "";
    }
}

三. 调用示例

//最终获取的时间值为Long类型的时间戳
String timestamp = HttpServerTime.getServerTimestamp();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值