spacer

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

home / web / dev / proxy

The Client Side

Developer News
Eclipse Helios Update Brings New PHP Tools
Internet Explorer 9 Ups Standards Support
JBoss Portal 5 Release Easier to Use

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

webref The latest from WebReference.com Browse >
Flashmaps' DynamicLocator: Interactive Maps for Small Areas · Flashmaps' AreaSelector: Interactive Maps for Wide Areas · The DB Mapper: Interactive Street-level Maps of U.S. and Canada
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
MS Access and MySQL · Cisco AutoQoS: VoIP QoS for Mere Mortals · While VoIP Adoption Explodes in Enterprise, Carrier Spending Lags

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

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