Hi Omkar,
> 1) How do i forward the actual request and response ?
First you need to extract the hostname to connect to. In the HTTP
request, you have something like:
GET /something HTTP/1.1
Host:
www.yahoo.com ...
So we need to parse the line containing Host and extract
www.yahoo.com. and then open a connection and forward everything to the host
www.yahoo.com. 2) After getting the response in the inputStream, how do i forward this response back to the browser who made the request ?
you can do a loop like this:
// forward the response from the server to the browser
InputStream sis = hostSocket.getInputStream();
OutputStream bos = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = sis.read(buffer);
if (n > 0) {
bos.write(buffer, 0, n);
}
} while (n > 0);
3) Can the HttpRequest and HttpResponse and Session objects available in java be of any help to us ?
Are you referring to those used in servlets? If you write your program in a servlet, that may be useful.
Below, you find the code of a simple proxy.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleProxyServer {
public static final int portNumber = 5555;
public static void main(String[] args){
SimpleProxyServer proxyServer = new SimpleProxyServer();
proxyServer.start();
}
public void start(){
System.out.println("Starting the SimpleProxyServer ...");
try {
ServerSocket serverSocket = new ServerSocket(MyProxyServer.portNumber,1);
byte[] buffer = new byte[10000];
while(true){
Socket clientSocket = serverSocket.accept();
InputStream bis = clientSocket.getInputStream();
// reading the request and put it into buffer
int n = bis.read(buffer);
String browserRequest = new String(buffer, 0, n);
System.out.println(browserRequest);
// extract the host to connect to
int start = browserRequest.indexOf("Host: ") + 6;
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end - 1);
System.out.println("Connecting to host " + host);
// forward the response from the proxy to the server
Socket hostSocket = new Socket(host, 80);
OutputStream sos = hostSocket.getOutputStream();
System.out.println("Forwarding request to server");
sos.write(buffer, 0, n);
sos.flush();
// forward the response from the server to the browser
InputStream sis = hostSocket.getInputStream();
OutputStream bos = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = sis.read(buffer);
System.out.println("Receiving " + n + " bytes");
if (n > 0) {
bos.write(buffer, 0, n);
}
} while (n > 0);
bos.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope it helps,
Cheers,
Francois