JGit私有Token连接GitHub库

有时需要通过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。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值