Thursday 8 May 2014

Java client read content from URL with SSL

  • Java client
  • import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLSession;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URISyntaxException;
    import java.net.URL;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    public class PDFTester {
        private static final int FILE_BUFFER_SIZE = 2048;
        public static final String CONTENT_TYPE_PDF = "application/pdf";
        public static byte[] readPDFFromURL(URL url) throws IOException {
            System.setProperty("javax.net.ssl.trustStore", "C:/temp/myCA.jks");
            System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
    
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
            httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            httpsURLConnection.connect();
    
            byte[] buffer = new byte[FILE_BUFFER_SIZE];
            int lengthOfByteToBeWrite;
            try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                 InputStream inputStream = httpsURLConnection.getInputStream()) {
                while ((lengthOfByteToBeWrite = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, lengthOfByteToBeWrite);
                }
                byteArrayOutputStream.flush();
                return byteArrayOutputStream.toByteArray();
            } catch (IOException e) {
                throw e;
            }
        }
    
        public static void main(String[] args) throws IOException, URISyntaxException {
            URL url = new URL("https://www.sample.com/pdf");
            byte[] bytes = readPDFFromURL(url);
            Path path = Paths.get("c:/temp/test.pdf");
            Files.write(path, bytes);
        }
    }
    
  • SSL base knowledge:
    Implementing SSL / TLS using Java