6

I am able to clone repo using clone command in JGit

Repo is http and of course it's failing to clone when I am behind proxy

Could you help me with code sample how to configure JGit with proxy in java

thanks!

Alan Harper
  • 793
  • 1
  • 10
  • 23

2 Answers2

12

JGit uses the standard ProxySelector mechanism for the Http connection. As of Today, the field org.eclipse.jgit.transport.TransportHttp.proxySelector used by the framework, is not overridable. It is configurable, though, customizing the JVM default proxy selector as in:

ProxySelector.setDefault(new ProxySelector() {
    final ProxySelector delegate = ProxySelector.getDefault();

    @Override
    public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied
        if (uri.toString().contains("github")
                && uri.toString().contains("https")) {
            return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress
                    .createUnresolved("localhost", 3128)));
        }
        if (uri.toString().contains("github")
                && uri.toString().contains("http")) {
            return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress
                    .createUnresolved("localhost", 3129)));
        }
            // revert to the default behaviour
        return delegate == null ? Arrays.asList(Proxy.NO_PROXY)
                : delegate.select(uri);
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        if (uri == null || sa == null || ioe == null) {
            throw new IllegalArgumentException(
                    "Arguments can't be null.");
        }
    }
});
Carlo Pellegrini
  • 5,656
  • 40
  • 45
3

In complement of Carlo Pellegrini answer, if your proxy requires some authentication, you should configure an Authenticator, like (based on Authenticated HTTP proxy with Java question):

    Authenticator.setDefault(new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            // If proxy is non authenticated for some URLs, the requested URL is the endpoint (and not the proxy host)
            // In this case the authentication should not be the one of proxy ... so return null (and JGit CredentialsProvider will be used)
            if (super.getRequestingHost().equals("localhost")) {
                return new PasswordAuthentication("foo", "bar".toCharArray());
            }
            return null;
        }
    });

    ProxySelector.setDefault(new ProxySelector() {...});
Alix Lourme
  • 1,135
  • 1
  • 11
  • 21