Skip to content

Commit a765e9a

Browse files
committed
feat: added convenience method for proxy config
1 parent b1445d0 commit a765e9a

3 files changed

Lines changed: 536 additions & 5 deletions

File tree

README.md

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@ A lightweight HTTP/HTTPS proxy library with pluggable interceptors and full MITM
2424
HttpProxy proxy = new HttpProxy();
2525
proxy.start(8080);
2626

27-
HttpClient client = HttpClient.newBuilder()
28-
.proxy(ProxySelector.of(new InetSocketAddress("localhost", 8080)))
29-
.build();
27+
HttpClient client = proxy.configureClient(HttpClient.newBuilder()).build();
3028

3129
HttpResponse<String> response = client.send(
3230
HttpRequest.newBuilder().uri(URI.create("http://example.com")).build(),
@@ -117,8 +115,7 @@ tmf.init(trustStore);
117115
SSLContext sslContext = SSLContext.getInstance("TLS");
118116
sslContext.init(null, tmf.getTrustManagers(), null);
119117

120-
HttpClient client = HttpClient.newBuilder()
121-
.proxy(ProxySelector.of(new InetSocketAddress("localhost", 8080)))
118+
HttpClient client = proxy.configureClient(HttpClient.newBuilder())
122119
.sslContext(sslContext)
123120
.build();
124121
```

src/main/java/org/codejive/tproxy/HttpProxy.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.codejive.tproxy;
22

33
import java.io.IOException;
4+
import java.net.InetSocketAddress;
5+
import java.net.ProxySelector;
46
import java.net.http.HttpClient;
57
import java.net.http.HttpRequest;
68
import java.net.http.HttpRequest.BodyPublishers;
@@ -282,6 +284,20 @@ public int port() {
282284
return port;
283285
}
284286

287+
/**
288+
* Configure an HttpClient.Builder to use this proxy.
289+
*
290+
* @param builder the HttpClient.Builder to configure
291+
* @return the same builder instance for chaining
292+
* @throws IllegalStateException if the proxy is not running
293+
*/
294+
public HttpClient.Builder configureClient(HttpClient.Builder builder) {
295+
if (!running) {
296+
throw new IllegalStateException("Proxy must be running before configuring clients");
297+
}
298+
return builder.proxy(ProxySelector.of(new InetSocketAddress("localhost", port)));
299+
}
300+
285301
private static HttpClient buildHttpClient(SSLContext sslContext) {
286302
HttpClient.Builder builder =
287303
HttpClient.newBuilder()

0 commit comments

Comments
 (0)