import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/*
 * Created on Mar 8, 2008
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Ramamoorthy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class TestTimeOut {

	public static void main(String[] args) 
	{
		try
		{
			  int timeOut = 1000; // TimeOut in Milliseconds
			  String urlPassed = "http://localhost:8080/SampleApplication/SampleServlet"; // URL
//			 It will throw Socket Closed Exception if timeout occurs
			  URL url = new URL((URL)null, urlPassed, new HttpTimeoutHandler(timeOut)); 
			  URLConnection connection = url.openConnection();
	  	      connection.setDoInput(true);
	  	      connection.setDoOutput(true);
	  	      connection.setUseCaches(false);
	  	      /** Passing Parameter to Servlet **/
	  	      PrintStream printer = new PrintStream(connection.getOutputStream());
	  	      printer.println("name=aaaaa");
	  	      printer.flush();
	  	      /** Reading Response **/
	  	      InputStream inStream = connection.getInputStream();
	  	      BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));

	  	      String line = reader.readLine();
	  	      StringBuffer sBuffer = new StringBuffer();
	  	      while( line != null )
	  	      {
	  	        sBuffer.append(line);
	  	        sBuffer.append("\n");
	  	        line = reader.readLine();
	  	      }
	  	      inStream.close();
	  	      
		} 
		catch(SocketTimeoutException e)
  	    {
  			System.out.println( "Socket Closed " + e.getMessage() );
  		}
  		catch(IOException e)
  		{
  			System.out.println( "IO Exception " + e.getMessage() );
		}
	}
}
