Java URL Connections

Java URL Connections allow a Java program -- either an applet or an application -- to use conventional Java I/O resources to communicate with a Web server and, hence, a Java Servlet.  That is, it can use Java InputStreams, OutputStreams, and appropriate Readers and Writers to send data back and forth.  The practice of communicating using a URLConnection is sometimes referred to as HTTP Tunnelling.

The motivation for URLConnections is that they enable so-called thick clients to interact with URL objects, such as a Servlet, in much the same way that an HTML form can interact with a Servlet.  Thus, the client could perform data checking or provide other processing either before or after a communication with a server.  For example, it an Applet discovered an input error in a data filed, it could request that the user correct the error before sending the data to a server.  And, of course, these clients have all of the processing power and GUI resources provided by Java as opposed to the limited resources provided by HTML.

Architecturally, when the client writes to a a URLConnection, the data is encapsulated in an HTTP message and when it reads, it reads data that is similarly returned as part of an HTTP message.  On the server side, such data when directed to a Servlet will become available in the doPost method through the HttpServletRequest InputStream.  However, it must be read from that Stream using an appropriate Reader rather than relying on the Servlet's getParameterNames or getParameterValues methods.

Resources necessary to work with URLConnections can be found in the java.net package.  There are also a number of on-line tutorials available, including A New Era for Java Protocol Handlers and Reading from and Writing to a URLConnection, both provided by Sun.


Client Side Connection and I/O

  try  {
            
            url = new URL("http://wwwj.cs.unc.edu:8888/jbs/servlet/ServletURLConnection");
            URLConnection urlConnection = url.openConnection();

            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true); 

            urlConnection.setUseCaches (false);
            urlConnection.setDefaultUseCaches (false);
            
            urlConnection.setRequestProperty("Content-Type", "text/plain");

	    PrintWriter out = new PrintWriter( urlConnection.getOutputStream() );
				
	    out.print("userAction=someAction");
	        
	    out.flush();
	    out.close();

	    BufferedReader in = new BufferedReader(
		new InputStreamReader(
		urlConnection.getInputStream()));
				
	    String inputLine;
	    String inputValue = "";

	    while ((inputLine = in.readLine()) != null)  {
	            inputValue = inputValue + inputLine;
	    }
	    in.close();
		// inputValue ready for use
            
        }  catch ( Exception e )  {
            e.printStackTrace();
        }
 

Server Side Connection and I/O

public void doPost (HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException
    {
	resp.setContentType("text/plain");
	PrintWriter out = resp.getWriter();
	            
        BufferedReader in = new BufferedReader(
				new InputStreamReader(
				req.getInputStream()));
				
	String inputLine;
	String userParamString = "";

	while ((inputLine = in.readLine()) != null)  {
	        userParamString = userParamString + inputLine;
	}
	    
	in.close();

	Hashtable userParams = HttpUtils.parseQueryString( userParamString );
	    
        String[] userActions = (String[])userParams.get("userAction");
        String userAction= userActions[0];
        
        if ( userAction.equalsIgnoreCase("someAction")){
            out.println( /*return some data*/ );
	    }
	    else {
            out.println("0");
	    }        

    }  // end doPost