Wednesday, February 25, 2009

Finding Protocol Type using Java

HTTP is the most widely used communication protocol of the internet. But nowadays HTTPS is also coming up and catching up with its secured connections. HTTPS provides encryption while transmitting data packets and provides a 3rd party verification of the server, confirming that a url is a valid one and that it actually represents the body which it claims to be representing. 

This java code snippet differentiates a given url by categorizing it as HTTP or HTTPS

ProtocolType.java

import java.net.*;

import javax.net.*;

import javax.net.ssl.*;

import java.io.IOException;

/**

 * @author Shazin Sadakath

 *

**/

public class ProtocolType{

              public static void main(String[] args){

                       try{

                                        URL url = new URL(args[0]);

                                        URLConnection connection = url.openConnection();

                                        connection.connect();

 

                                        if(connection instanceof HttpURLConnection){

                                                       System.out.println(”This is a valid HTTP Protocol”);

                                        }else if(connection instanceof HttpsURLConnection){

                                                       System.out.println(”This is a valid HTTPS Protocol”);

                                        }else{

                                                       System.out.println(”This is a unrecognized Protocol”);

                                        }

                       }catch(ArrayIndexOutOfBoundsException aiobe){

                                        usage();

                       }catch(MalformedURLException mue){

                                         System.out.println(”Not a valid URL”);

                       }catch(IOException ioe){

                                         System.out.println(”Can not Connect to ” + args[0]);

                       }

          }

 

           private static void usage(){

                           System.out.println(”Usage: ProtocolType \n Ex: ProtocolType http://coderpassion.wordpress.com”);

           }

}

If you are in a network which uses a proxy server to connect to the internet use

$ java -Dhttp.proxyHost= ProtocolType

No comments:

Post a Comment