Click here to Skip to main content
15,125,968 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am developing a proxy programin java.It works properly for some sites.It doesnt work for some site which enforces SSL or which respond with 302 found. Tell how can i fix that




Java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package miniproject;

/**
 *
 * @author SYSTEM
 */

import java.io.*;
import java.net.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SimpleProxyServer extends Thread {
    
    int bytesRead;
    PrintWriter out;
    Socket client=null;
//    public SimpleProxyServer(Socket client){
//        this.client=client;
//    }
    
    
    
  /**
   * runs a single-threaded proxy server on
   * the specified local port. It never returns.
     * @param host
     * @param remoteport
     * @param localport
     * @throws java.io.IOException
   */
   @Override
  public void run() {
      try {
          int remoteport=80;
          int temp=0;
          int datalimit=10;
          
         // Create a ServerSocket to listen for connections with
          HttpRequest request1=null;
          HttpRequest2 request2=null;
          InetAddress address=null;
          String username=" ";
          int userid=0;
          ServerSocket ss = new ServerSocket(90);
          final byte[] request = new byte[8192];
          final byte[] response = new byte[8192];
          byte[] reply = new byte[8192];
          while (true) {
              Socket client = null;
              Socket server = null;
            client = ss.accept();
              //System.out.println("\n Ip Address from client port"+client.getInetAddress());
              try {
                  String add= client.getInetAddress().toString();
                  Sqlconnection con=new Sqlconnection();
                  ResultSet rs=con.select("select * from user where status='online'");
                  while(rs.next()){
                      String s = rs.getString("ipaddress");
                      username=rs.getString("username");
                      userid=rs.getInt("userid");
                      if(s.equals(add))
                          temp=1; //existing connection
                  }
                  rs.close();
                  con.close();
                  if(temp==0){//If it is a new connection
                      try {
                          
                          request1 = new HttpRequest(client);
                          request1.process(add);
                           // System.out.println("address:"+address);
                       }
                      catch (Exception ex) {
                          Logger.getLogger(SimpleProxyServer.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                else { //---------------------Online user Forward request
//                        request2 = new HttpRequest2(client,username,userid);
//                        request2.process(add);
                        ////# edited user web server instead of internet                      
// Wait for a connection on the local port
                        final InputStream streamFromClient = client.getInputStream();
                        final OutputStream streamToClient = client.getOutputStream();
                        //#edited
                        bytesRead= streamFromClient.read(request);
                        String browserRequest = new String(request, 0, bytesRead);
                        System.out.println("\nFrom client:"+browserRequest);
                        //#edited sending 200 ok
                       if(browserRequest.contains("CONNECT")){                           
                            String StatusLine="HTTP/1.0 200 OK";
                           // String ContentTypeLine="Content-type: txt/html";
                            BufferedOutputStream o=new BufferedOutputStream(streamToClient);
                            o.write(StatusLine.getBytes());
                           // o.write(ContentTypeLine.getBytes());	
                        }
          //                request[0]='G';
          //                request[1]='E';
          //                request[2]='T';
          //                request[3]=32;
          //                for(int i=4;i<bytesread;i++){>
          //                    request[i]=request[i+4];                    
          //                }
          //                bytesRead=bytesRead-4;
//            }
                        //Saving to DB
                        Sqlconnection scn=new Sqlconnection();
                        int end = browserRequest.indexOf('\n');
                        String url=browserRequest.substring(0,end);
                        scn.update("INSERT INTO userlog VALUES('"+username+"','"+url+"', CURRENT_TIME, CURRENT_DATE, "+userid+"); ");
                        scn.close();
                        //
              int start = browserRequest.indexOf("Host: ") + 6;
              end = browserRequest.indexOf('\n', start);
              String host = browserRequest.substring(start, end - 1);
              System.out.println("\nConnecting to host: " + host);
              // Make a connection to the real server.
              // If we cannot connect to the server, send an error to the
              // client, disconnect, and continue waiting for connections.
              try {
                  //Address addring =10.32.0.2;
                  server = new Socket(host,80);
              } 
              catch (IOException e) {
                  out = new PrintWriter(streamToClient);
                  out.print("Proxy server cannot connect to " + host + ":"
                          + remoteport + ":\n" + e + "\n");
                  out.flush();
                  client.close();
                  
                   continue;
              }
                      System.out.println("connection established");
              // Get server streams.
              final InputStream streamFromServer = server.getInputStream();
              final OutputStream streamToServer = server.getOutputStream();
              
              Thread t;
              t = new Thread() {
                  @Override
                  public void run() {
                      //bytesRead;
                      try {
                          
                          streamToServer.write(request, 0, bytesRead);
                          streamToServer.flush();
                          System.out.println("\nto server:"+new String(request, 0, bytesRead));
                          while ((bytesRead = streamFromClient.read(request)) != -1) {
                              streamToServer.write(request, 0, bytesRead);
                              streamToServer.flush();
                          }
                      } catch (IOException e) {
                          System.err.println(e);
                      }
                      
                      // the client closed the connection to us, so close our
                      // connection to the server.
//                      try {
//                      ///    streamToServer.close();
//                      } catch (IOException e) {
//                      }
                  }
              };
              
              // Start the client-to-server request thread running
              t.start();
              
              // Read the server's responses
              // and pass them back to the client.
              //    int bytesRead;
              try {
                  //System.out.println("Writing to client:\n");
//                int a= streamFromServer.read(response);
//                String clienrre = new String(response, 0, a);
//                System.out.println(clienrre);
                  //#edited
                  while ((bytesRead = streamFromServer.read(reply)) != -1) {
                      
                      streamToClient.write(reply, 0, bytesRead);
                      streamToClient.flush();
                      System.out.println("\nWriting to client:\n"+new String(reply, 0, bytesRead));
//                    out.print(new String(reply, 0, bytesRead));
//                    out.flush();
                  }
              } catch (IOException e) {
                  System.err.println(e);
              }
              
              // The server closed its connection to us, so we close our
              // connection to our client.
              //fixed socket close exception
              //streamToClient.close();
          }
      } catch (IOException e) {
          System.err.println("\nerror:\n"+e);
      } catch (SQLException ex) {
          Logger.getLogger(SimpleProxyServer.class.getName()).log(Level.SEVERE, null, ex);
      }       catch (Exception ex) {
                  Logger.getLogger(SimpleProxyServer.class.getName()).log(Level.SEVERE, null, ex);
              } finally {
          try {
              if (server != null)
                  server.close();
              if (client != null)
                  client.close();
          } catch (IOException e) {
              System.err.println(e);
          }
      }
            }  
      
        } catch (IOException ex) {
            Logger.getLogger(SimpleProxyServer.class.getName()).log(Level.SEVERE, null, ex);
  }
      
}
}

Posted
Updated 7-May-15 5:03am
v2
Comments
Richard MacCutchan 3-May-15 3:03am
   
Please format your code properly with <pre> tags, and explain exactly where the error occurs.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900