J2EE - Connecting To HTTPS Site Using Simple Java Program When USing Proxy

In some cases we may have to connect to an HTTPS Site using simple Java Program when proxy is involved. Here in this article we are going to see how to connect. Here we are using HttpsURLConnection class.

 package com.test;  
 import javax.net.ssl.HandshakeCompletedEvent;  
 import javax.net.ssl.HandshakeCompletedListener;  
 import javax.net.ssl.SSLSocket;  
 import weblogic.security.SSL.SSLSocketFactory;  
 import weblogic.net.http.HttpsURLConnection;  
 import java.io.BufferedReader;  
 import java.io.BufferedWriter;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 import java.io.OutputStream;  
 import java.io.OutputStreamWriter;  
 import java.io.PrintWriter;  
 import java.io.UnsupportedEncodingException;  
 import java.net.Socket;  
 import java.net.UnknownHostException;  
 /**  
  * @author murali  
  *  
  */  
 public class JavaSSL {  
      public static void main(String[] args) throws Exception {                 
           new JavaSSL().makeConnection();            
      }  
      private void makeConnection() throws UnknownHostException, IOException{  
           int port = 443;  
           String hostname = "gmail.com";  
           String proxyHost = "";  
           String proxyPort = "";  
        String tunnelHost;  
        int tunnelPort;  
           SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();  
           System.out.println("Creating a SSL Socket For "+hostname+" on port "+port);  
        System.setProperty("https.proxyHost", proxyHost);  
        System.setProperty("https.proxyPort", proxyPort);  
        tunnelHost = System.getProperty("https.proxyHost");  
        tunnelPort = Integer.getInteger("https.proxyPort").intValue();  
        Socket tunnel = new Socket(tunnelHost, tunnelPort);  
        doTunnelHandshake(tunnel, hostname, port);  
        SSLSocket socket = (SSLSocket)factory.createSocket(tunnel, hostname, port, true);  
        socket.addHandshakeCompletedListener(  
           new HandshakeCompletedListener() {  
             public void handshakeCompleted(  
                  HandshakeCompletedEvent event) {  
                System.out.println("Handshake finished ... ");  
                System.out.println("\t CipherSuite:" + event.getCipherSuite());  
                System.out.println("\t SessionId " + event.getSession());  
                System.out.println("\t PeerHost " + event.getSession().getPeerHost());  
             }  
           }  
        );  
           socket.startHandshake();  
           System.out.println("Handshake Completed ... ");  
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));  
        out.flush();  
        if (out.checkError())  
           System.out.println("SSLSocketClient: java.io.PrintWriter error");  
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
        String inputLine;  
        while ((inputLine = in.readLine()) != null)  
           System.out.println(inputLine);  
        in.close();  
        out.close();  
        socket.setEnableSessionCreation(false);  
        socket.close();  
        tunnel.close();  
      }  
   private void doTunnelHandshake(Socket tunnel, String host, int port) throws IOException{  
                OutputStream out = tunnel.getOutputStream();  
                String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n"  
                        + "User-Agent: "  
                        + sun.net.www.protocol.http.HttpURLConnection.userAgent  
                        + "\r\n\r\n";  
                byte b[];  
                try {  
                  b = msg.getBytes("ASCII7");  
                } catch (UnsupportedEncodingException ignored) {  
                  b = msg.getBytes();  
                }  
                out.write(b);  
                out.flush();  
                byte          reply[] = new byte[200];  
                int          replyLen = 0;  
                int          newlinesSeen = 0;  
                boolean          headerDone = false;     /* Done on first newline */  
                InputStream     in = tunnel.getInputStream();  
                while (newlinesSeen < 2) {  
                  int i = in.read();  
                  if (i < 0) {  
                     throw new IOException("Unexpected EOF from proxy");  
                  }  
                  if (i == '\n') {  
                     headerDone = true;  
                     ++newlinesSeen;  
                  } else if (i != '\r') {  
                     newlinesSeen = 0;  
                     if (!headerDone && replyLen < reply.length) {  
                       reply[replyLen++] = (byte) i;  
                     }  
                  }  
                }  
   }  
 }  
You need to mention proxyHost and proxyPort for your proxy.

You need to mention hostname also. Here in this program I used gmail.com.

Note: When running this program you should keep weblogic.jar and wlfullclient.jar in the class path and also you should use the argument -Dweblogic.security.SSL.ignoreHostnameVerification=true

If you place the above program with proxyHost, proxyPort and hostname in the folder ssltest in package com.test (D:\ssltest\com\test\JavaSSL.java), please find the below steps to execute.

 set path=%path%;D:\bea121\jdk160_29\bin;  
 set classpath=%classpath%;D:\bea121\wlserver_12.1\server\lib\weblogic.jar;D:\bea121\wlserver_12.1\server\lib\wlfullclient.jar;  
 D:\ssltest\com\test>javac JavaSSL.java  
 D:\ssltest>java -Dweblogic.security.SSL.ignoreHostnameVerification=true com.test.JavaSSL  
 <Aug 19, 2012 1:49:24 PM IST> <Info> <Security> <BEA-090905> <Disabling CryptoJ  
 JCE Provider self-integrity check for better startup performance. To enable this  
  check, specify -Dweblogic.security.allowCryptoJDefaultJCEVerification=true>  
 <Aug 19, 2012 1:49:24 PM IST> <Info> <Security> <BEA-090906> <Changing the defau  
 lt Random Number Generator in RSA CryptoJ from ECDRBG to FIPS186PRNG. To disable  
  this change, specify -Dweblogic.security.allowCryptoJDefaultPRNG=true>  
 Creating a SSL Socket For gmail.com on port 443  
 Handshake finished ...  
      CipherSuite:SSL_RSA_WITH_RC4_128_SHA  
      SessionId [Session-1, SSL_RSA_WITH_RC4_128_SHA]  
      PeerHost 148.87.19.20  
 Handshake Completed ...  

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today