Using HttpUrlConnection
The java.net.HttpUrlConnection class provides the main way to access HTTP resources from Java. To establish an HTTP connection, you can use code like the following:
String path = "http://example.com";
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
This code sets up a URL initialized with a link to example.com. The openConnection() method on the URL then returns HttpUrlConnection. Once you have HttpUrlConnection, you can set the HTTP method (HEAD, in this case). You can get data from the server, upload data to the server, and specify request headers.
With HttpUrlConnection, you can call setRequestProperty() to specify a request header:
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
Each request generates a response, which may be successful or not. To check the response, get the response code:
int responseCode...