首页 > 解决方案 > Java代理https实现

问题描述

我尝试制作自己的代理服务器,并且已经为我的代理服务器实现了 http 支持。代理服务器工作正常。现在我也想拥有 https(仅使用套接字)。我在https://www.rfc-editor.org/rfc/rfc2817查找了我必须做的事情。在我的功能中,我尝试建立一个 TLS 隧道。使用我的方法,我只能得到一种不允许作为响应的方法。我还检查了互联网上的一些来源,但没有找到任何可以帮助我解决问题的东西。

这是我的功能。

private Socket openTLSTunnel(String host) throws IOException {
    String raw_request = "CONNECT " + host + ":80 HTTP/1.1\n"
            + "Host: " + host + ":80"
            + "\r\n\r\n";

    // Make a connection to the website.
    Socket tunnel = new Socket();
    int timeout = 10000;
    var server = new InetSocketAddress(host, 80);
    tunnel.connect(server, timeout);


    // Write the request to server.
    OutputStream out = tunnel.getOutputStream();
    byte[] msg = raw_request.getBytes(StandardCharsets.UTF_8);
    out.write(msg);
    out.flush();

    // TODO send error to client.
    // Get the response from server.
    InputStream in = tunnel.getInputStream();
    byte reply[] = new byte[200];
    int replyLen = 0;
    int newlinesSeen = 0;
    boolean headerDone = false;

    while (newlinesSeen < 2) {
      int i = in.read();
      if (i < 0) {
        throw new IOException("Unexpected EOF from proxy");
      }
      if (i == '\n') {
        headerDone = true;
        ++newlinesSeen;
      }
      else if (i != '\r') {
        newlinesSeen = 0;
        if (!headerDone && replyLen < reply.length) {
          reply[replyLen++] = (byte) i;
        }
      }
    }
    String replyStr = new String(reply, 0, replyLen, "ASCII7");

    // Check if connection established.
    if(!replyStr.toLowerCase().contains("200 connection established")) {
      System.out.println("No TLS connection established!");
      throw new AccessDeniedException(replyStr);
    }
    else{
      System.out.println("Connection established!");
    }

    return tunnel;
  }

提前致谢!

标签: javasocketshttpsproxy

解决方案


推荐阅读