Proxy HTTP en Java avec interface utilisateur


Pour vous simplifier la vie voici le version java du proxy http.
Voilà à quoi ça ressemble:







Les deux popups servent à configurer le proxy, le port sur lequel il écoute et si il doit se connecter vers un autre proxy ou pas.
La fenêtre principale est découpée en deux partie, à gauche le texte reçu du browser, à droite celui reçu du serveur. Tant que le checkbox n'est pas selectionné le message n'est pas envoyé, il est donc possible de modifier la requête avant de l'envoyer.

n:cal SetSyn('java')
:so $VIMRUNTIME/syntax/2html.vim
t
import java.net.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*;

public class GProxy extends JFrame
{

  public class ProxyDialog extends JDialog
  {
    JTextField hostTF, portTF;

    public ProxyDialog(Frame parent, boolean modal)
    {
      super(parent, modal);

      JPanel panel1, panel2, panel3;
      JButton okButton, cancelButton;

      Container contentPane = this.getContentPane();

      panel1 = new JPanel();
      panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add(panel1, BorderLayout.SOUTH);
      okButton = new JButton("OK");
      panel1.add(okButton);
      cancelButton = new JButton("Cancel");
      panel1.add(cancelButton);

      panel2 = new JPanel();
      panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add( panel2, BorderLayout.NORTH);
      panel2.add(new JLabel("Proxy ? "));
      panel2.add(useProxy);

      panel3 = new JPanel();
      panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add(panel3, BorderLayout.CENTER);
      hostTF = new JTextField(proxy, 20);
      portTF = new JTextField("" + proxyport, 5);
      panel3.add(hostTF);
      panel3.add(portTF);

      setTitle("Proxy info");
      pack();


      cancelButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event)
        {
          dispose();
          setVisible(false);
        }
      });

      okButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event)
        {
          proxy = hostTF.getText();
          proxyport = Integer.parseInt(portTF.getText());
          dispose();
          setVisible(false);
        }
      });

    }
  }


  public class PortDialog extends JDialog
  {
    JTextField portTF;

    public PortDialog(Frame parent, boolean modal)
    {
      super(parent, modal);

      JPanel panel1, panel3;
      JButton okButton, cancelButton;

      Container contentPane = this.getContentPane();

      panel1 = new JPanel();
      panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add(panel1, BorderLayout.SOUTH);
      okButton = new JButton("OK");
      panel1.add(okButton);
      cancelButton = new JButton("Cancel");
      panel1.add(cancelButton);

      panel3 = new JPanel();
      panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add(panel3, BorderLayout.CENTER);
      panel3.add(new JLabel("Proxy port"));
      portTF = new JTextField("" + port, 5);
      panel3.add(portTF);

      setTitle("Proxy info");
      pack();


      cancelButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event)
        {
          dispose();
          setVisible(false);
        }
      });

      okButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event)
        {
          port = Integer.parseInt(portTF.getText());
          try {
            s.close();
            s = new ServerSocket(port);
          } catch (Exception e) {};
          dispose();
          setVisible(false);
        }
      });

    }
  }

  class OneServeur extends Thread {
    private Socket socket, socketToWeb;
    private BufferedReader fromBrowser;
    private PrintWriter toBrowser;
    private PrintWriter toWeb;
    private BufferedReader fromWeb;

    public OneServeur() throws IOException {
      start();
    }

    public void run() {
      while ( true ) {
        try {
          socket = s.accept();

          fromBrowser = new BufferedReader(
                            new InputStreamReader ( socket.getInputStream()));
          toBrowser = new PrintWriter(
                           new BufferedWriter (
                                  new OutputStreamWriter (
                                        socket.getOutputStream())),true);

          String str, targetHost="", httpHeader="";
          while(true) {
               str = fromBrowser.readLine();
               httpHeader += str + "\r\n";
               if ( str.startsWith("Host: " ) ) targetHost = str.substring(6);
               if ( str.length() == 0 ) break;
          }

          if ( useProxy.isSelected() )
            socketToWeb = new Socket(InetAddress.getByName(proxy),proxyport);
          else
            socketToWeb = new Socket(InetAddress.getByName(targetHost),80);

          fromWeb = new BufferedReader(
                          new InputStreamReader ( socketToWeb.getInputStream()));
          toWeb = new PrintWriter(
                          new BufferedWriter (
                            new OutputStreamWriter (
                                  socketToWeb.getOutputStream())),true);

          TAfromBw.setText(httpHeader);

          while ( ! autoBw.isSelected() ) sleep(500) ;
          toWeb.println(TAfromBw.getText());

          TAfromWeb.setText("");
          while ( true ) {
               str = fromWeb.readLine();
               if ( str == null ) break;
               TAfromWeb.append(str+"\r\n");
          }


          while ( ! autoWeb.isSelected() )  sleep(500) ;

          toBrowser.println(TAfromWeb.getText());
          socket.close();
          socketToWeb.close();
        } catch ( Exception e) {
        }
      }
    }
  }


  public int port = 12345;
  public int proxyport = 8080;
  public String  proxy = "proxy";
  private ServerSocket s;
  private JCheckBox useProxy = new JCheckBox("", true);
  private JCheckBox autoBw = new JCheckBox("", false);
  private JCheckBox autoWeb = new JCheckBox("", false);
  private JTextArea TAfromBw = new JTextArea(10,20);
  private JTextArea TAfromWeb = new JTextArea(10,20);

  public GProxy() throws IOException {
    JMenuBar menuBar = new JMenuBar();
    JButton closeButton = new JButton("Close");
    JPanel bwPanel = new JPanel();
    JPanel bwCmd = new JPanel();
    JPanel webPanel = new JPanel();
    JPanel webCmd = new JPanel();
    JScrollPane webPane, bwPane;


    Container contentPane = this.getContentPane();

    JPanel Core = new JPanel();
    Core.setLayout(new BorderLayout());
    bwPanel.setLayout(new BorderLayout());
    webPanel.setLayout(new BorderLayout());

    setJMenuBar(menuBar);

    JMenu fMenu = new JMenu("File");
    menuBar.add(fMenu);

    JMenuItem proxyItem = new JMenuItem("Set Proxy", 2);
    fMenu.add(proxyItem);
    JMenuItem portItem = new JMenuItem("Set Port", 2);
    fMenu.add(portItem);
    fMenu.addSeparator();
    JMenuItem exitItem = new JMenuItem("Exit", 2);
    fMenu.add(exitItem);

    webPane = new JScrollPane(TAfromWeb,
                               JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                               JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    bwPane = new JScrollPane(TAfromBw,
                               JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                               JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    webCmd.add(new JLabel("Send")); webCmd.add(autoWeb);
    bwCmd.add(new JLabel("Send")); bwCmd.add(autoBw);

    webPanel.add(webPane, BorderLayout.NORTH );
    bwPanel.add(bwPane, BorderLayout.NORTH );
    webPanel.add(webCmd, BorderLayout.SOUTH );
    bwPanel.add(bwCmd, BorderLayout.SOUTH );

    Core.add(bwPanel, BorderLayout.WEST);
    Core.add(webPanel, BorderLayout.EAST);


    contentPane.add(Core);


    // add listeners for the window and the various buttons
    this.addWindowListener( new WindowAdapter(){
         public void windowClosing(WindowEvent e){
              setVisible(false);
              dispose();
              System.exit(0);
    }});

    exitItem.addActionListener( new ActionListener(){
         public void actionPerformed(ActionEvent e){
              System.exit(0);
    }});

    proxyItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            changeProxy();
    }});

    portItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            changePort();
    }});

    pack();

    s = new ServerSocket(port);
    new OneServeur();

  }

  protected void changeProxy()
  {
    new ProxyDialog(this, true).show();
  }

  protected void changePort()
  {
    new PortDialog(this, true).show();
  }


  public static void main ( String args[] ) {
    try {
      (new GProxy()).setVisible(true);
    } catch ( Exception e ) {}