有时需要通过Java代码连接Git库,开源的JGit是不错选择。JGit连接代码仓库通常需要鉴权,这里介绍一种使用私有Token进行鉴权连接的方法。
首先在Git库上生成私有Token,Github中生成路径为:Settings -> Developer settings -> Personal access tokens -> Generate new token,最终生成Token字符串,需要牢记,后面使用。
JGit连接Git仓库时,使用CredentialsProvider进行鉴权,私有Token使用UsernamePasswordCredentialsProvider对象进行设置,进行数据库连接即可,代码如下:
package com.king.jgit.service;
import java.io.File;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
public class JGitService {
public Git getGit(String repositoryUrl, String privateToken, String repositoryDir)
throws InvalidRemoteException, TransportException, GitAPIException {
CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN",
privateToken);
Git git = Git.cloneRepository().setCredentialsProvider(credentialsProvider).setURI(repositoryUrl)
.setDirectory(new File(repositoryDir)).call();
return git;
}
}
其中需要注意的是,UsernamePasswordCredentialsProvider构建方法,第一个参数为用户名,这个用户名在使用私有Token 的时候,必须固定的设置为“PRIVATE-TOKEN”,第二个参数即为上面生成的Git库私有Token。