forked from robaho/httpserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTunnelProxyTest.java
More file actions
76 lines (60 loc) · 2.9 KB
/
TunnelProxyTest.java
File metadata and controls
76 lines (60 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import javax.net.ssl.SSLContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import jdk.test.lib.net.SimpleSSLContext;
import jdk.test.lib.net.URIBuilder;
import robaho.net.httpserver.extras.ProxyHandler;
/**
* @test
* @summary test ability to create a tunneling proxy server using the CONNECT request method
*/
public class TunnelProxyTest {
public static void main(String[] args) throws Exception {
System.setProperty("jdk.httpclient.HttpClient.log","all");
InetAddress loopback = InetAddress.getLoopbackAddress();
InetSocketAddress addr = new InetSocketAddress (loopback, 0);
SSLContext sslContext = new SimpleSSLContext().get();
var server1 = HttpsServer.create(addr,100);
server1.setHttpsConfigurator(new HttpsConfigurator(sslContext));
var proxy = HttpServer.create(addr,100);
var ctx = proxy.createContext("/", new ProxyHandler());
server1.createContext("/test", (HttpExchange exchange) -> {
System.out.println("request headers: "+exchange.getRequestHeaders());
exchange.sendResponseHeaders(200,0);
if(exchange.getRequestMethod().equals("POST")) {
exchange.getRequestBody().transferTo(exchange.getResponseBody());
exchange.getResponseBody().close();
} else {
try (var os = exchange.getResponseBody()) {
os.write("hello".getBytes());
}
}
});
proxy.start();
server1.start();
try {
var client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress(proxy.getAddress().getHostName(),proxy.getAddress().getPort())))
.sslContext(sslContext )
.build();
try(client) {
var uri = URIBuilder.newBuilder().scheme("https").host(server1.getAddress().getHostName()).port(server1.getAddress().getPort()).path("/test").build();
var response = client.send(HttpRequest.newBuilder(uri).build(),HttpResponse.BodyHandlers.ofString());
if(!response.body().equals("hello")) throw new IllegalStateException("incorrect body "+response.body());
// response = client.send(HttpRequest.newBuilder(uri).POST(HttpRequest.BodyPublishers.ofString("senditback")).build(),HttpResponse.BodyHandlers.ofString());
// if(!response.body().equals("senditback")) throw new IllegalStateException("incorrect body "+response.body());
}
} finally {
server1.stop(0);
proxy.stop(0);
}
}
}