Last active
November 5, 2023 10:30
-
-
Save mannprerak2/26cee00a8e971428403e80daf97a219a to your computer and use it in GitHub Desktop.
Configure java netty HttpClient to use a proxy server in spring boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A helper class to configure a http proxy. | |
* | |
* Spring autoconfigures this as it implements HttpClientCustomizer for gateway | |
* outbound requests, but any webclient must manually call this. | |
*/ | |
@Component | |
public class LocalProxyConfig implements HttpClientCustomizer { | |
@Override | |
public HttpClient customize(HttpClient httpClient) { | |
// Configure http proxy. | |
if (StringUtils.isNotBlank(System.getProperty("http.proxyHost"))) { | |
httpClient = httpClient.resolver(new LocalProxyNameResolverGroup( | |
System.getProperty("http.proxyHost"), | |
Integer.parseInt(System.getProperty("http.proxyPort", "80")))); | |
} | |
return httpClient; | |
} | |
@AllArgsConstructor | |
public final class LocalProxyNameResolverGroup extends AddressResolverGroup<InetSocketAddress> { | |
private final String proxyHost; | |
private final Integer proxyPort; | |
@Override | |
protected AddressResolver<InetSocketAddress> newResolver(EventExecutor executor) throws Exception { | |
return new LocalProxyInetSocketAddressResolver(executor, proxyHost, proxyPort); | |
} | |
} | |
public class LocalProxyInetSocketAddressResolver extends AbstractAddressResolver<InetSocketAddress> { | |
private final String proxyHost; | |
private final Integer proxyPort; | |
public LocalProxyInetSocketAddressResolver(EventExecutor executor, String proxyHost, Integer proxyPort) { | |
super(executor, InetSocketAddress.class); | |
this.proxyHost = proxyHost; | |
this.proxyPort = proxyPort; | |
} | |
@Override | |
protected boolean doIsResolved(InetSocketAddress address) { | |
return !address.isUnresolved(); | |
} | |
@Override | |
protected void doResolve(final InetSocketAddress unresolvedAddress, final Promise<InetSocketAddress> promise) | |
throws Exception { | |
try { | |
promise.setSuccess(new InetSocketAddress(SocketUtils.addressByName(proxyHost), proxyPort)); | |
} catch (Exception e) { | |
promise.setFailure(e); | |
} | |
} | |
@Override | |
protected void doResolveAll(final InetSocketAddress unresolvedAddress, | |
final Promise<List<InetSocketAddress>> promise) throws Exception { | |
try { | |
promise.setSuccess(List.of(new InetSocketAddress(SocketUtils.addressByName(proxyHost), proxyPort))); | |
} catch (Exception e) { | |
promise.setFailure(e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment