spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / web / dev / proxy

The Client Side

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

On the client side, a small class, HttpProxyConnection, is used to handle communications with the server. Its primary method is fetch(), which does the actual network communication. The bold portion below handles the equivalent to service() on the client end. It sends the PROXY command, reads in the content-length, and then reads that many characters into a buffer.

    public byte[] fetch(URL proxyURL) throws Exception {
    	System.out.println("fetching " + proxyURL.toString() + " using proxy at " +
    		proxyHost + ":" + proxyPort);
    	Socket sock = new Socket(proxyHost, proxyPort);
    
    	InputStream in = sock.getInputStream();
    	DataInputStream urlData = new DataInputStream(in);
    	OutputStream out = sock.getOutputStream();
    	PrintStream cmdStream = new PrintStream(out);
    
    	// fetch past the first line
    	urlData.readLine();
    
    	// send a PROXY command
    	cmdStream.println("PROXY " + proxyURL.toString());
    
    	// get the status
    	String cmdResult = urlData.readLine();
    	System.out.println(cmdResult);
    	if (cmdResult.regionMatches(0, "+OK", 0, 3)) {
    		int contentLength = Integer.parseInt(urlData.readLine().substring(17));
    		byte[] dataBuffer = new byte[contentLength];
    		byte[] chunk = new byte[512];
    		int count;
    		int bytesRead = 0;
    
    		// fetch the whole piece of data into a byte array
    		while (bytesRead <= contentLength) {
    			count=urlData.read(chunk);
    			bytesRead += count;
    			byte[] t= new byte[dataBuffer.length + count];
    			System.arraycopy(dataBuffer, 0, t, 0, dataBuffer.length);
    			System.arraycopy(chunk, 0, t, dataBuffer.length, count);
    			dataBuffer= t;
    		}
    
    		// send a QUIT command
    		cmdStream.println("QUIT");
    		sock.close(); 	
    		return dataBuffer;
    	}
    	else {
    		sock.close();
    		throw new Exception("proxy error: " + cmdResult);
    	}
    }
    

Comments are welcome

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business

Created: Oct. 27, 1997
Revised: Oct. 30, 1997

URL: http://webreference.com/dev/proxy/client.html