package com.jqyd.pub.time; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.util.Date; import org.apache.http.entity.StringEntity; import org.json.JSONException; import org.json.JSONObject; import android.os.SystemClock; import com.jqyd.pub.string.JqydStringUtil; import com.jqyd.pub.transport.SendServer; public class GetFromServer { /** * 获取服务器端时间 * @return */ public static long getServerTime(){ long serverTime = 0; SntpClient client = SntpClient.getInstance(); if (client.requestTime("cn.pool.ntp.org", 60000)) { serverTime= client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference(); } if(serverTime==0){ JSONObject object = new JSONObject(); try { object.put("getTime", "yes"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 请求服务器 String urlStr =""; SendServer sendMsg = new SendServer(urlStr); StringEntity entity; try { entity = new StringEntity(JqydStringUtil.switchEncode(object.toString())); String result = sendMsg.requestJsonFromServer(entity); if (result != null && !result.equals("-1") && !result.equals("500")) { try { JSONObject obj = new JSONObject(result); serverTime = obj.getLong("timeSec"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { URL url = new URL("http://www.bjtime.cn");// 取得资源对象 URLConnection uc = url.openConnection();// 生成连接对象 uc.connect(); // 发出连接 serverTime= uc.getDate(); // 取得网站日期时间 } catch (Exception e) { e.printStackTrace(); } } } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } Date current = new Date(serverTime); //获取网络时间 return serverTime; } }