Webreference-Getting out of the Sandbox: Building an Applet Proxy Server | 2
![]() ![]() ![]() ![]() ![]()
|
The Client Side
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
Created: Oct. 27, 1997Revised: Oct. 30, 1997
URL: http://webreference.com/dev/proxy/client.html





