2013-06-04 25 views
5

代理配置,我能夠在JGit使用clone命令來克隆回購JGit代碼

回購是http,當然它的失敗

你能幫助我的代碼示例如何克隆當我身後代理

在java中使用代理配置JGit

謝謝!

+2

您是否嘗試過使用在JVM級別設置HTTP代理的經典方法? – fge

+0

在問題中提到,我需要在代碼中進行設置... –

+1

如果使用標準方式,它的工作原理就是如此。你的問題並沒有真正說明。 – fge

回答

8

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."); 
     } 
    } 
}); 
1

在卡羅佩萊格里尼回答的補充,如果你的代理服務器需要一些認證,你應該配置一個Authenticator,像(基於Authenticated HTTP proxy with Java問題):

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() {...});