JGit是使用JAVA的API來操控Git倉庫的庫,由Eclipse公司維護。他提供的API分成兩個層次,底層命令和高層命令。底層API是直接作用於低級的倉庫對象,高層的API是一個面向普通用戶級別功能友好的前端。
JGit主要通過SSH和HTTP(S)的方式與遠程倉庫進行交互,此外也可以用Git協議(只讀)。通過這兩種方式,必然是需要添加驗證信息的。介紹如下:
(1)HTTPS - https://example.com/repo.git
CloneCommand cloneCommand = Git.cloneReposity();
CloneCommand通過setCredentialsProvider()的方法,通過賦值一個UsernamePasswordCredentialsProvider對象,來提供用戶名和密碼登陸。
(不建議使用HTTP的方式傳送,但是也可行)
(2)SSH with Public Key -
其實通過公鑰訪問的鏈接:
git@***.***.***/user/***.git
而SSH利用公鑰的訪問方式的認證信息,通過JSCH庫提供。而在JGit中提供了JschConfigSessionFactory的抽象類,代碼如下:
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure( Host host, Session session ) { /* 解除HostKey檢查,也就意味着可以接受未知的遠程主機的文件,這是不安全的,這種模式只是用於測試為目的的。 利用ssh-keyscan -t rsa hostname,收集主機數據。 */ session.setConfig("StrictHostKeyChecking","no"); } };
以下這是在command中注冊認證信息:
cloneCommand.setTransportConfigCallback( new TransportConfigCall back(){ public void configure(Transporttransport){ SshTransport sshTransport=(SshTransport)transport; sshTransport.setSshSessionFactory(sshSessionFactory); } }
(3)SSH with Password - ssh://user@example.com/repo.git
使用的是上述JschConfigSessionFactory重寫的configure方法中,設置password,具體就不詳述了。