java - 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;
}
提前致谢!
解决方案
推荐阅读
- c# - 如何在下一个列表附近添加添加项目
- spring - 立面层的推荐注释是什么?
- java - 如何使用 Java 中的 RSAPrivateKeySpec 类从字符串创建 RSA PrivateKey?
- python - 将大整数除以 10 并截断小数在 python 中不起作用
- node.js - ts-node 抛出错误:找不到模块,尽管它在 tsconfig 中有
- zip - 如何验证 Zip 文件的 CRC-32 计算
- java - TypeError:无法读取未定义(frida)的属性“重载”
- java - 为什么我的 Java 代码更改在从命令行运行但在 Eclipse 中工作时没有反映?
- tensorflow2.0 - 调整图像大小并为 tensorflow 2 数据集创建 tfexample 导致错误
- reactjs - 从切片访问全局状态