Java HTTPS client example
April 05, 2011 08:04:37 Last update: April 05, 2011 08:11:37
There's no difference between a Java HTTP client and a Java HTTPS client. Ignore JavaWorld Java Tip 96, it's way too old. The following code gets an HTTP page as well as an HTTPS page.
There's one catch. If you are using the code on a test server with a self-signed certificate, it fails. In that case, I would suggest that you download the certificate from the server and import it to your keystore as a trusted key. You may also need to add a subject alternative name to the certificate if the host name does not match the certificate.
You may also choose to use a custom
import java.io.*; import java.net.*; public class HTTPGet { public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: java HTTPGet <url>"); return; } URL url = new URL(args[0]); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) ); String line = in.readLine(); while (line != null) { System.out.println(line); line = in.readLine(); } } }
There's one catch. If you are using the code on a test server with a self-signed certificate, it fails. In that case, I would suggest that you download the certificate from the server and import it to your keystore as a trusted key. You may also need to add a subject alternative name to the certificate if the host name does not match the certificate.
You may also choose to use a custom
TrustManager and HostnameVerifier to ignore the certificate verification errors.