当我使用getWebsiteLongtime()获取日期时,为什么时间值始终为0?
private static String webUrl = "https://www.baidu.com";
private static long getWebsiteLongtime(String webUrl) {
try {
URL url = new URL(webUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.connect();
long time = uc.getDate();
return time;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Date().getTime();
}
答案 0 :(得分:0)
一个问题:您的AndroidManifest中是否拥有“互联网”权限?
<uses-permission android:name="android.permission.INTERNET"/>
另一方面,我试图用这个进行快速测试并且有效:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<String, Void, String>(){
private String time = "";
@Override
protected String doInBackground(String... strings) {
return String.valueOf(getWebsiteLongtime(webUrl));
}
@Override
protected void onPostExecute(String t) {
time = t;
Log.i(TAG, "TIME: " + time);
}
}.execute();
}
private static long getWebsiteLongtime(String webUrl) {
try {
URL url = new URL(webUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.connect();
long time = uc.getDate();
Log.d(TAG, "Time 1: " + time);
return time;
} catch (IOException e) {
Log.e(TAG, "Exception!", e);
}
Log.d(TAG, "Time 2: " + new Date().getTime());
return new Date().getTime();
}
日志是:
11-23 10:13:06.366 31893-31935 / com.archison.tests.myapplication D / MainActivity:Time 1:1479892387000
11-23 10:13:06.367 31893-31893 / com.archison.tests.myapplication I / MainActivity:TIME:1479892387000
希望我帮助过:)