Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Get server date from remote host in Java programmatically

In this post I will describe how can you get a date from Remote Server in Java.

Date objects in Java are quite common. Usually if you want to get the current date and time you just need to create new instance of java.util.Date:

new Date();

It is simply and straight forward in most cases. It returns whatever current date is on the client machine. 

But there might be a case when you want to have the actual date from the Remote Server. It is useful for example if you have trial version of your software and would like to check the real date or in general if the time is very important thing in your application.

Remote host date and time can be get from connection header. Example code below:
--------------------------------------------------------------------------------------------------------------------
01. Date remoteDate = null;
02. URL url = new URL(REMOTE_SERVER_URL);
03. URLConnection urlConn = url.openConnection();
04. HttpURLConnection conn = (HttpURLConnection) urlConn;
05. conn.setConnectTimeout(10000);
06. conn.setReadTimeout(10000);
07. conn.setInstanceFollowRedirects( true );
08. conn.setRequestProperty( "User-agent", "spider" );
09. conn.connect();
20. Map> header = conn.getHeaderFields();
21. for (String key : header.keySet()) {
22.     if (key != null && "Date".equals(key)) {
23.         List data = header.get(key);
24.         String dateString = data.get(0);
25.         SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
26.         remoteDate = sdf.parse(dateString);
27.         break;

28.     }
29. }
--------------------------------------------------------------------------------------------------------------------

Some notes for this code example:

Line 22. Some of the key from header map fields may be null and we are interested only in 'Date' field.

Line 25. This one depends on the date format returned by the server. In this example it is valid for example for:
Sat, 13 Oct 2012 17:57:50

And that's it - you got a date :) 



This post first appeared on IT Code Hub - Java, Mobile Apps, Linux And More, please read the originial post: here

Share the post

Get server date from remote host in Java programmatically

×

Subscribe to It Code Hub - Java, Mobile Apps, Linux And More

Get updates delivered right to your inbox!

Thank you for your subscription

×