我可以在 JGit 中使用 clone 命令克隆 repo
回购是http,当然当我在代理后面时它无法克隆
你能帮我提供代码示例如何在 java 中使用代理配置 JGit
谢谢!
JGit 使用标准ProxySelector
的 Http 连接机制。截至今天,org.eclipse.jgit.transport.TransportHttp.proxySelector
框架使用的字段是不可覆盖的。不过,它是可配置的,可以自定义 JVM 默认代理选择器,如下所示:
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 回答的补充,如果您的代理需要一些身份验证,您应该配置一个Authenticator
,例如(基于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() {...});