Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.net.InetSocketAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.nio.ByteBuffer;
- import java.nio.charset.Charset;
- public class WebProxy {
- public static void main(String[] args) {
- try {
- // create a socket
- ServerSocket servSocket = new ServerSocket(8000);
- // sockets for client and server communication
- Socket client, server;
- while(true) {
- System.out.println("Waiting...");
- client = servSocket.accept();
- System.out.println("Accepted connection : " + client);
- System.out.println("");
- BufferedInputStream fromClient = new BufferedInputStream(client.getInputStream());
- BufferedOutputStream toClient = new BufferedOutputStream(client.getOutputStream());
- byte[] request, response;
- StringBuffer host = new StringBuffer("");
- int port = 80;
- request = getHTTPData(fromClient, host, true);
- String hostName = host.toString();
- server = new Socket();
- server.connect(new InetSocketAddress(hostName, port));
- BufferedInputStream serverIn = new BufferedInputStream(server.getInputStream());
- BufferedOutputStream serverOut = new BufferedOutputStream(server.getOutputStream());
- // send the request out
- serverOut.write(request);
- serverOut.flush();
- streamHTTPData(serverIn, toClient, true);
- serverIn.close();
- serverOut.close();
- // String subRequest = fromClient.readLine();
- // String url = extractUrl(subRequest);
- // String host = url.split("/")[2];
- // subRequest = subRequest.replaceAll("https?://" + host, "");
- // int port = 80;
- // while(!subRequest.equals("")) {
- // request += subRequest + "\r\n";
- // subRequest = in.readLine();
- // }
- // System.out.println("The HTTP request is: ");
- // System.out.println(request);
- // // Check if host is blocked.
- //
- // Socket toServer = new Socket();
- // //TODO place a handler for bad hosts
- // toServer.connect(new InetSocketAddress(host, port));
- // System.out.println("Connected: " + url);
- //
- // PrintWriter serverOut = new PrintWriter(toServer.getOutputStream(), true);
- // serverOut.println(request);
- // System.out.println("Request sent");
- //
- // BufferedReader serverIn = new BufferedReader(new InputStreamReader(toServer.getInputStream(), "UTF8"));
- // String response = "";
- // String subResponse;
- // System.out.println("");
- // System.out.println("Response is received");
- // while ((subResponse = serverIn.readLine()) != null) {
- // System.out.println(subResponse);
- // response += subResponse + "\r\n";
- // }
- //
- // PrintWriter clientIn = new PrintWriter(fromClient.getOutputStream(), true);
- // clientIn.println(response);
- // System.out.println("Dealt with client");
- }
- }
- catch(Exception e){
- e.printStackTrace();
- }
- }
- private static byte[] getHTTPData (InputStream in, StringBuffer host, boolean waitForDisconnect) {
- // get the HTTP data from an InputStream, and return it as
- // a byte array, and also return the Host entry in the header,
- // if it's specified -- note that we have to use a StringBuffer
- // for the 'host' variable, because a String won't return any
- // information when it's used as a parameter like that
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- streamHTTPData(in, bs, host, waitForDisconnect);
- return bs.toByteArray();
- }
- private static int streamHTTPData (InputStream in, OutputStream out,
- StringBuffer host, boolean waitForDisconnect)
- {
- // get the HTTP data from an InputStream, and send it to
- // the designated OutputStream
- StringBuffer header = new StringBuffer("");
- String data = "";
- int responseCode = 200;
- int contentLength = 0;
- int pos = -1;
- int byteCount = 0;
- try
- {
- // get the first line of the header, so we know the response code
- data = readLine(in);
- if (data != null)
- {
- header.append(data + "\r\n");
- pos = data.indexOf(" ");
- if ((data.toLowerCase().startsWith("http")) &&
- (pos >= 0) && (data.indexOf(" ", pos+1) >= 0))
- {
- String rcString = data.substring(pos+1, data.indexOf(" ", pos+1));
- try
- {
- responseCode = Integer.parseInt(rcString);
- } catch (Exception e) {
- // if (debugLevel > 0)
- // debugOut.println("Error parsing response code " + rcString);
- }
- }
- }
- // get the rest of the header info
- while ((data = readLine(in)) != null)
- {
- // the header ends at the first blank line
- if (data.length() == 0)
- break;
- header.append(data + "\r\n");
- // check for the Host header
- pos = data.toLowerCase().indexOf("host:");
- if (pos >= 0)
- {
- host.setLength(0);
- host.append(data.substring(pos + 5).trim());
- }
- // check for the Content-Length header
- pos = data.toLowerCase().indexOf("content-length:");
- if (pos >= 0)
- contentLength = Integer.parseInt(data.substring(pos + 15).trim());
- }
- // add a blank line to terminate the header info
- header.append("\r\n");
- // convert the header to a byte array, and write it to our stream
- out.write(header.toString().getBytes(), 0, header.length());
- // if the header indicated that this was not a 200 response,
- // just return what we've got if there is no Content-Length,
- // because we may not be getting anything else
- if ((responseCode != 200) && (contentLength == 0))
- {
- out.flush();
- return header.length();
- }
- // get the body, if any; we try to use the Content-Length header to
- // determine how much data we're supposed to be getting, because
- // sometimes the client/server won't disconnect after sending us
- // information...
- if (contentLength > 0)
- waitForDisconnect = false;
- if ((contentLength > 0) || (waitForDisconnect))
- {
- try {
- byte[] buf = new byte[4096];
- int bytesIn = 0;
- while ( ((byteCount < contentLength) || (waitForDisconnect))
- && ((bytesIn = in.read(buf)) >= 0) )
- {
- out.write(buf, 0, bytesIn);
- byteCount += bytesIn;
- }
- } catch (Exception e) {
- // String errMsg = "Error getting HTTP body: " + e;
- // if (debugLevel > 0)
- // debugOut.println(errMsg);
- //bs.write(errMsg.getBytes(), 0, errMsg.length());
- }
- }
- } catch (Exception e) {
- // if (debugLevel > 0)
- // debugOut.println("Error getting HTTP data: " + e);
- }
- //flush the OutputStream and return
- try { out.flush(); } catch (Exception e) {}
- return (header.length() + byteCount);
- }
- private static String readLine (InputStream in)
- {
- // reads a line of text from an InputStream
- StringBuffer data = new StringBuffer("");
- int c;
- try
- {
- // if we have nothing to read, just return null
- in.mark(1);
- if (in.read() == -1)
- return null;
- else
- in.reset();
- while ((c = in.read()) >= 0)
- {
- // check for an end-of-line character
- if ((c == 0) || (c == 10) || (c == 13))
- break;
- else
- data.append((char)c);
- }
- // deal with the case where the end-of-line terminator is \r\n
- if (c == 13)
- {
- in.mark(1);
- if (in.read() != 10)
- in.reset();
- }
- } catch (Exception e) {
- }
- // and return what we have
- return data.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement