-2

Why the time value is always 0 when I use getWebsiteLongtime() to get the date?

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();
    }
IIIIIIIIIIIIIIIIIIIIII
  • 3,958
  • 5
  • 45
  • 70
ToNext
  • 3
  • 2

1 Answers1

0

One question: do you have the "Internet" permission in your AndroidManifest?

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

On the other hand, I've tried to do a fast test with this and it worked:

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

The log was:

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

Hope I helped :)

Archison
  • 81
  • 5
  • thank you for your answer sincerely. I tried, and some sites can, and some sites do not, should be the site of the restrictions. – ToNext Nov 24 '16 at 01:24