试图在java中处理来自浏览器的HTTP连接请求

试图在java中处理来自浏览器的HTTP连接请求,java,sockets,ssl,Java,Sockets,Ssl,我真的想更好地理解如何处理连接HTTP请求过程。在我正在构建的HttpServer中,我陷入了困境,希望其他人能帮助我激励我如何应对下一个挑战。到目前为止,关于我的代码的一些信息。我有一个类HTTPServer在端口8080上监听一个套接字(最初是一个非SSL套接字)。我有一个名为DefaultHttpRequestHandler的类,该类包含一个HTTPClient实例,该实例处理服务器需要发出的所有请求,HttpServer中的一个工作线程处理将浏览器发送的所有请求发送到端口8080 我的问

我真的想更好地理解如何处理连接HTTP请求过程。在我正在构建的HttpServer中,我陷入了困境,希望其他人能帮助我激励我如何应对下一个挑战。到目前为止,关于我的代码的一些信息。我有一个类HTTPServer在端口8080上监听一个套接字(最初是一个非SSL套接字)。我有一个名为DefaultHttpRequestHandler的类,该类包含一个HTTPClient实例,该实例处理服务器需要发出的所有请求,HttpServer中的一个工作线程处理将浏览器发送的所有请求发送到端口8080

我的问题如下:

  • 当连接请求进入并发送到DefaultHttpRequestHandler时,它将被传递到句柄(HttpRequest请求、HttpResponse响应、HttpContext上下文)方法。在这一点上,我偷看了一下请求,如果我看到它是一个连接,那么下一步是什么?我想然后在端口8080上建立SSL套接字连接,这是在普通套接字之前?或者我总是持有两个套接字,一个作为标准套接字,另一个作为ssl,而不是切换到ssl套接字。这部分真的让我很沮丧,我很困惑如何编写这个笨蛋 DefaultHttpServer.java-服务器 DefaultRequestHandler.java—从代理服务器向服务器发送请求的客户端 }

    RequestListenerThread-这是我的httpserver中处理调度请求的run方法
    接收
    CONNECT
    请求(并接受该请求)的代理不会执行任何SSL/TLS初始化或处理(如果执行了,则可能是潜在的MITM攻击者)。它只是在目标HTTPS主机和初始客户端之间来回传递所有通信量

    这些答案可能更详细:


    您需要的是能够掌握底层套接字(或输入/输出流),并在另一端写入读取的每个字节。

    这些信息确实有帮助,谢谢您。但是,它没有回答我关于如何处理SSL部分的主要问题。从您提供的这些链接来看,代理服务器似乎可以使用标准套接字侦听来自浏览器的传入http请求。如果是这样,为什么会存在serversocket和sslserversocket。我假设代理服务器将是默认的套接字连接,而不是在您看到sslsocket的连接开关之后,但这不起作用,因为浏览器通过的任何纯文本都会引发异常。为什么这是如此令人困惑!不,您可能误解了,但是代理绝对不做任何与SSL相关的事情。它根本不会切换到SSLSocket。它只是打开到目标HTTPS服务器的TCP连接,将从初始客户端读取的内容写入该服务器,并将从该服务器读取的内容写回客户端。代理服务器根本不使用SSLServerSocket(除非浏览器和代理之间的连接本身是通过SSL完成的,但这是非常不寻常的)。您可能遇到的困难是,我不确定是否可以从处理程序中获得的
    HttpRequest
    实例访问初始客户端套接字。您需要它的I/O流才能通过隧道将它们传输到目标HTTPS服务器。因为一旦您使用了
    CONNECT
    ,您就不再真正使用HTTP(在浏览器和代理之间),所以准备
    HttpResponse
    实例就没有意义了。
     public class DefaultHttpServer {
    
    public static void main(String[] args) throws Exception {
    
        Thread t = new RequestListenerThread(8080);
        t.setDaemon(false);
        t.start();
    
        //send a request to proxy server for testing
        testSendReqFromClient() ;
    }
    
    public static void testSendReqFromClient() throws Exception
    {
    
        SSLContext sslCtx = SSLContext.getInstance("TLS");
    
        //  sslCtx.init(null,new TrustManager[] { new EasyX509TrustManager() }, null);
    
    
            sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                System.out.println("getAcceptedIssuers =============");
                                return null;
                        }
    
                        public void checkClientTrusted(X509Certificate[] certs,
                                        String authType) {
                                System.out.println("checkClientTrusted =============");
                        }
    
                        public void checkServerTrusted(X509Certificate[] certs,
                                        String authType) {
                                System.out.println("checkServerTrusted =============");
                        }
    
                        @Override
                        public void checkClientTrusted(
                                java.security.cert.X509Certificate[] arg0,
                                String arg1) throws CertificateException {
                            // TODO Auto-generated method stub
    
                        }
    
                        @Override
                        public void checkServerTrusted(
                                java.security.cert.X509Certificate[] arg0,
                                String arg1) throws CertificateException {
                            // TODO Auto-generated method stub
    
                        }
            } }, new SecureRandom());
    
        Thread.sleep(5000);
        SSLSocketFactory sf = new SSLSocketFactory(sslCtx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(https);
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        schemeRegistry.register(http);
        BasicHttpRequest req = new BasicHttpRequest("GET","https://www.yahoo.com");
        ThreadSafeClientConnManager tm = new ThreadSafeClientConnManager(schemeRegistry);
        HttpClient httpClient = new DefaultHttpClient(tm);
        ConnRouteParams.setDefaultProxy(req.getParams(), new HttpHost("localhost",8080,"http"));
        httpClient.execute(new RequestWrapper(req));
    }
    
     }
    
     public class DefaultHttpRequestHandler implements HttpRequestHandler {
    
    private static String sslType = "TLS";
    private HttpClient httpClient = null;
    private ThreadSafeClientConnManager tm;
    public DefaultHttpRequestHandler() {
        super();
        init();
    
    }
    
    private void init() {
        try {
            SSLContext sslCtx = SSLContext.getInstance(sslType);
    
        //  sslCtx.init(null,new TrustManager[] { new EasyX509TrustManager() }, null);
    
    
            sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                System.out.println("getAcceptedIssuers =============");
                                return null;
                        }
    
                        public void checkClientTrusted(X509Certificate[] certs,
                                        String authType) {
                                System.out.println("checkClientTrusted =============");
                        }
    
                        public void checkServerTrusted(X509Certificate[] certs,
                                        String authType) {
                                System.out.println("checkServerTrusted =============");
                        }
    
                        @Override
                        public void checkClientTrusted(
                                java.security.cert.X509Certificate[] arg0,
                                String arg1) throws CertificateException {
                            // TODO Auto-generated method stub
    
                        }
    
                        @Override
                        public void checkServerTrusted(
                                java.security.cert.X509Certificate[] arg0,
                                String arg1) throws CertificateException {
                            // TODO Auto-generated method stub
    
                        }
            } }, new SecureRandom());
    
        SSLSocketFactory sf = new SSLSocketFactory(sslCtx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    
    
            Scheme https = new Scheme("https", 443, sf);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(https);
    
            Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
            schemeRegistry.register(http);
    
            tm = new ThreadSafeClientConnManager(schemeRegistry);
            //httpClient = new  ContentEncodingHttpClient(tm);
            httpClient = new DefaultHttpClient(tm);
            httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); 
            //httpClient.getConnectionManager().getSchemeRegistry()         .register(https);
    
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    
    }
    
    public void handle(HttpRequest request, HttpResponse response,
            HttpContext context) throws HttpException, IOException {
    
        System.out.println(request);
        RequestLine reqLine = request.getRequestLine();
        if(reqLine.getMethod().equalsIgnoreCase("CONNECT"))
        {
    
            response.setEntity(new BufferedHttpEntity(new StringEntity("HTTP/1.0 200 Connection established\r\nProxy-agent: proxy client\r\n\r\n")));
            //do i switch the socket to sslsocketconnection in defaulthttpserver here?
        }
        else
        {
            try {
    
                HttpResponse clientResponse = null;
    
                HttpEntity entity = null;
    
                clientResponse = httpClient.execute(new RequestWrapper(request));
    
                entity = clientResponse.getEntity();
    
                if (entity != null) {
                    response.setEntity(new BufferedHttpEntity(entity));
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
                e.printStackTrace();
            } 
    
        }
    
    }
    
     class RequestListenerThread extends Thread {
    
        private static ServerSocket sslServersocket = null;
        private static ServerSocket serversocket = null;
         static ServerSocketFactory ssocketFactory  = null;
        private final HttpParams params;
        private final HttpService httpService;
        Selector selector ;
    
        public RequestListenerThread(int port) throws Exception {
    
    
            KeyStore ks = KeyStore.getInstance("JKS");  
            ks.load(new FileInputStream("privateKey2.store"), "whitehatsec123".toCharArray());
    
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, "whitehatsec123".toCharArray());
    
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(kmf.getKeyManagers(), null, null);
    
    
            ssocketFactory = context.getServerSocketFactory();
            //serversocket =  ssocketFactory.createServerSocket(port);
            serversocket = new ServerSocket(port);
            this.params = new SyncBasicHttpParams();
            this.params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true).setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 50000)
                    .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
                            8 * 1024)
                    .setBooleanParameter(
                            CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
                    .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
                    .setParameter(CoreProtocolPNames.ORIGIN_SERVER,
                            "HttpComponents/1.1");
            // Set up the HTTP protocol processor
            HttpProcessor httpproc = new ImmutableHttpProcessor(
                    new HttpResponseInterceptor[] { new ResponseDate(),
                            new ResponseServer(), new ResponseContent(),
                            new ResponseConnControl() });
    
            // Set up request handlers
            HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
            reqistry.register("*", new DefaultHttpRequestHandler());
    
            // Set up the HTTP service
            this.httpService = new HttpService(httpproc,
                    new DefaultConnectionReuseStrategy(),
                    new DefaultHttpResponseFactory(), reqistry, this.params);
        }
    
    
        public void run() 
        {
            System.out.println("Listening on port "
                    + serversocket.getLocalPort());
            while (!Thread.interrupted()) 
            {
                try 
                {
                    // Set up HTTP connection
                    Socket socket = serversocket.accept();
                    DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
                    System.out.println("Incoming connection from "
                            + socket.getInetAddress());
                    conn.bind(socket, this.params);
    
                    // Start worker thread
                    Thread t = new WorkerThread(this.httpService, conn);
                    t.setDaemon(true);
                    t.start();
                } catch (InterruptedIOException ex) {
                    break;
                } catch (IOException ex) {
                    System.err
                            .println("I/O error initialising connection thread: "
                                    + ex.getMessage());
                    ex.printStackTrace();
                    break;
                }
            }
        }
    
    
    }
    
    
    
    
    class WorkerThread extends Thread {
    
        private final HttpService httpservice;
        private final HttpServerConnection conn;
    
        public WorkerThread(final HttpService httpservice,
                final HttpServerConnection conn) {
            super();
            this.httpservice = httpservice;
            this.conn = conn;
        }
    
        public void run() {
            System.out.println("New connection thread");
            HttpContext context = new BasicHttpContext(null);
    
            try {
                while (!Thread.interrupted() && this.conn.isOpen()) {
                    this.httpservice.handleRequest(this.conn, context);
    
                }
            } catch (ConnectionClosedException ex) {
                System.err.println("Client closed connection");
            } catch (IOException ex) {
                System.err.println("I/O error: " + ex.getMessage());
                ex.printStackTrace();
            } catch (HttpException ex) {
                System.err.println("Unrecoverable HTTP protocol violation: "
                        + ex.getMessage());
            } finally {
                try {
                    this.conn.shutdown();
                } catch (IOException ignore) {
                }
            }
        }
    
    }