一、在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/#/