java实现简单的http代理

java http代理

初学java就写了个http代理练练手,把以前C语言写的移植了下,不得不说Java写起来是要比C语言简单的多。

  • LocalServer类 创建本地监听 接收客户端请求
package cn.lbxx;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class LocalServer{
    private static int   LPort   ;  // 监听端口
    private ServerSocket loSocket;  // 本地套接字
    public LocalServer() throws IOException {
        loSocket = new ServerSocket(LPort);
    }
    public void start()
    {
        try {
            System.out.println("run on " + LPort);
            while(true)
            {
                Socket ct = loSocket.accept();
                new HandleRequest(ct).start(); // 新建线程处理客户端请求
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        LPort = 8853;
        try {
            new LocalServer().start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • HandleRequest类 处理客户端请求
package cn.lbxx;

import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class HandleRequest extends Thread {
    private static String KHost = "Host:";
    
    private Socket       clSocket   ;
    private Socket       seSocket   ;
    private Scanner      cdata      ; 
    private String       remotehost ;
    private int          remoteport ;
    private boolean      https      ;
    private List bufflist   ;
    
    public HandleRequest(Socket c){
        this.clSocket = c;
        this.bufflist = new ArrayList();
    }
    
    public void run()
    {
        try {
            cdata = new Scanner(clSocket.getInputStream());
            int beginIndex = KHost.length() + 1;
            String line;
            // 读取客户端的请求头
            while(cdata.hasNextLine() && (line = cdata.nextLine()).length() != 0)
            {
                if(line.length() > 5)
                {
                    if(line.substring(0, KHost.length()).equals(KHost))
                    {
                        int hend;
                        if((hend = line.indexOf(':', beginIndex)) != -1)
                        {
                            remotehost = line.substring(beginIndex, hend);
                            remoteport = Integer.parseInt(line.substring(hend + 1));
                        } else {
                            remotehost = line.substring(beginIndex);
                            remoteport = 80;
                        }
                    }
                    // 判断是否为https请求
                    if(line.substring(0, line.indexOf(' ')).equals("CONNECT")){
                        https = true;
                    }
                    
                    if(line.matches("Proxy-Connection(.*)")){
                        line = "Connection: keep-alive";
                    }
                }
                bufflist.add(line);
            }
            
            if(remotehost != null)
            {
                System.out.println(remotehost + " -> " + remoteport + "  " + https);
                seSocket = new Socket(remotehost, remoteport); // 连接到远程主机
                if (https) { // 客户端与远程主机间数据转发
                    List list = new ArrayList<>();
                    list.add("HTTP/1.1 200 Connection Established");
                    
                    new ForwardData(list, seSocket, clSocket).start();
                    new ForwardData(null, clSocket, seSocket).start();
                } else {
                    toUri(bufflist);
                    
                    new ForwardData(bufflist, clSocket, seSocket).start();
                    new ForwardData(null, seSocket, clSocket).start();
                }
            }
        } catch (ConnectException c) {
            System.err.println("链接超时");
        } catch (SocketException se) {
            System.err.println("无法连接-> " + remotehost + ":" + remoteport);
        } catch (Exception e) {
            System.err.println("发生错误" + e);
        }
    }
    
    // 将header转换为path形式
    private void toUri(List buff)
    {
        for (int i = 0; i < buff.size(); i++)
        {
            String line = buff.get(i);
            String head = line.substring(0, line.indexOf(' '));
            int    hlen = head.length() + 1;
            if(line.substring(hlen, hlen + 7).equals("http://"))
            {
                String uri = line.substring(line.indexOf('/', hlen + 7));
                buff.set(i, head + " " + uri);
                break;
            }
        }
    }
}
  • ForwardData类 数据转发
package cn.lbxx

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

public class ForwardData extends Thread {
    private List buff        ;
    private Socket       source      ;
    private Socket       destination ;
    
    public ForwardData(List buff, Socket sou, Socket des) {
        this.buff        = buff;
        this.source      = sou ;
        this.destination = des ;
    }
    
    @Override
    public void run() {
        try {
            OutputStream outStream = destination.getOutputStream();
            InputStream  inStream  = source.getInputStream();

            if(buff != null && buff.size() > 0){
                for(String str : buff)
                {
                    outStream.write((str + "\r\n").getBytes());
                    outStream.flush();
                }
                outStream.write("\r\n".getBytes());
                outStream.flush();
            }

            byte[] bs = new byte[4096];
            int len;
            while ((len = inStream.read(bs)) != -1) {
                outStream.write(bs, 0, len);
                outStream.flush();
            }
            
            outStream.close();
            inStream.close();
        } catch (IOException ie) {
            System.err.println("http 数据转发异常 " + ie);
        }
    }
}
  • 测试
java实现简单的http代理_第1张图片
smallproxy.png

很简单的代理例子,问题有不少经过测试多数网站都能代理,性能速度方面就没去测试,多线程应该还不错吧,有空继续优化吧。

源码地址: https://github.com/lkl0304/SmallProxy

你可能感兴趣的:(java实现简单的http代理)