JAVA在本地建立远程git仓库

一、在git上建立第三方应用

在个人主页->个人设置->第三方应用->创建应用

详情请见:码云文档 https://gitee.com/api/v5/oauth_doc#/list-item-3

二、获取access_taken

建立第三方应用后可以获取该应用的Client Id和Client Secret,通过Client Id和Client Secret可以获取access_taken

详情请见:https://gitee.com/api/v5/oauth_doc#/list-item-2

三、建立远程仓库

获取access_taken后,调用git的API建立远程仓库

详情请见:https://gitee.com/api/v5/swagger#/postV5UserRepos

四、案例

1.获取access_taken

// 获取git的access_taken
//此处使用的HttpRequest和JSONUtil是使用的Hutool的http请求和JSON工具类
public static String getGitAccessTaken() {
		String url = "https://gitee.com/oauth/token?" + "grant_type=password"//grant_type授权方式,此处采用密码模式
				+ "&client_id=第三方应用的Client Id"
				+ "&client_secret=第三方应用的Client Serect"
				+ "&scope=user_info projects pull_requests issues notes keys hook groups gists enterprises"
				+ "&username=git账号" 
				+ "&password=git密码";
		String result = HttpRequest.post(url)
				.timeout(20000)// 超时,毫秒
				.header("Content-Type", "application/x-www-form-urlencoded")
				.execute()
				.body();
		String access = JSONUtil.parseObj(result).getStr("access_token");//获取access_token
		String refresh = JSONUtil.parseObj(result).getStr("refresh_token");//获取refresh_token
		return access;
	}

2、建立远程仓库

// 新增远程仓库
public static String addRemote(String homeWorkName) {
		String access = getGitAccessTaken();//获取access_taken
		JSONObject content = new JSONObject();
		content.put("access_token", access);//用户授权码
		content.put("name", homeWorkName);//仓库名称
		content.put("description", homeWorkName);//仓库描述
		content.put("homepage", "https://gitee.com");//主页(eg: https://gitee.com)
		content.put("has_issues", "true");//允许提Issue与否。默认: 允许(true)
		content.put("has_wiki", "true");//提供Wiki与否。默认: 提供(true)
		content.put("auto_init", "false");//值为true时则会用README初始化仓库。默认: 不初始化(false)
		content.put("gitignore_template", "Java");//Git Ingore模版
		content.put("license_template", "AGPL-3.0");//License模版
		content.put("private", "false");//仓库公开或私有。默认: 公开(false)

		String url = "https://gitee.com/api/v5/user/repos";//git的新建仓库API
		String requestJson = JSON.toJSONString(content);
		String result = HttpRequest.post(url).timeout(20000).body(requestJson).execute().body();

		httpsUrl=JSONUtil.parseObj(result).getStr("html_url");//获取仓库的http地址
		sshUrl=JSONUtil.parseObj(result).getStr("ssh_url");//获取仓库的ssh地址
		return sshUrl;
	}

Hutool详情请见:https://hutool.cn/docs/#/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值