Android 获取远程服务器时间

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

直接访问 http://quan.suning.com/getSysTime.do 可以看到接口提供的时间格式

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

里面有两个时间数据 sysTime2 和 sysTime1,都是常见的时间格式,但我们在计算和存储都是以时间戳的形式,所以获取到时间后会对其进行转换。

获取时间

由于是获取网络数据,需要在 Androidmanifest.xml 文件中申请网络使用权限。

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

再写一个网络请求的类,用于加载远程数据。

package com.example.gettime;

import android.util.Log;

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;

public class HttpHandler {

    private static final String TAG = "HttpHandler";

    public HttpHandler() {

    }

    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();
    }
}

以下是封装好的方法

获取时间 getServerTimestamp

public static final int getServerTimestamp() {
	final HttpHandler httpHandler = new HttpHandler();
	final String jsonStr = httpHandler.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 Integer.valueOf(new Date().getTime()/1000+"");
}

转换时间 dateToTimestamp

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

    return Integer.valueOf(date.getTime()/1000+"");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值