测试步行人

博客园 首页 新随笔 联系 订阅 管理

 


 Git是一个开源的分布式版本控制系统,可以有效、高速地处理从很小到非常大的项目版本管理。在公司一般用于代码管理;开发用例管理平台时我们选择使用git来管理用例,期间使用了很多git api。接下来我们就来讨论下如何通过git api达到我们的目的


 

在使用api之前我们需要获取授权,官网提供了三种方式获取Authentication:OAuth2 tokens、Personal access tokens、Session cookie,我们选择第二种private_token方式,这种方式最简单、最容易理解,只需要在http请求时设置header即可,如下

headers.put("private-token", gitUserToken);

 

下面介绍两种获取方法

一:/session接口方式

public static void main(String[] args) {
​
        System.err.println("private_token:"+getPrivateToken());
    }
​
    public static  String getPrivateToken(){
        //使用接口获取private_token  链接中需要填写登录用户的账号和密码
        //为了安全,这种获取方式建议使用postman调用下获取到数据即可,不要写在工程代码中
        HttpClientResponse httpClientResponse=httpClient("post","http://you git address:port/api/v4/session?login=loginName&password=loginPasswor","");
        if (httpClientResponse != null && "201".equals(httpClientResponse.getStateCode())) {
            JSONObject jsonObject =JSONObject.fromObject(httpClientResponse.getResponseBody());
            return jsonObject.getString("private_token");
        }
        return "";
    }
接口返回结果
{
    "name": "张三",
    "username": "zhangsan",
    "id": 415,
    "state": "active",
    "avatar_url": null,
    "web_url": "http://you git address:port/zhangsan",
    "created_at": "2020-02-17T02:45:26.594Z",
    "is_admin": false,
    "bio": "",
    "location": "",
    "skype": "",
    "linkedin": "",
    "twitter": "",
    "website_url": "",
    "organization": "",
    "last_sign_in_at": "2021-05-26T03:08:01.605Z",
    "confirmed_at": "2020-02-17T02:45:26.595Z",
    "email": "zhangsan@tsign.cn",
    "theme_id": 2,
    "color_scheme_id": 1,
    "projects_limit": 10,
    "current_sign_in_at": "2021-05-31T03:32:02.041Z",
    "identities": [
        {
            "provider": "ldapmain",
            "extern_uid": "uid=25100707-1941530886,ou=418347936,ou=72871007,ou=6617272,ou=1,dc=tsign,dc=cn"
        }
    ],
    "can_create_group": true,
    "can_create_project": true,
    "two_factor_enabled": false,
    "external": false,
    "private_token": "-zR8o18f3f3tnL_asdef"
}

 

二:页面创建

官网英文原文如下:     

      1、Log in to your GitLab account.
      2、Go to your Profile settings.
      3、Go to Access tokens.
      4、Choose a name and optionally an expiry date for the token.
      5、Choose the desired scopes.
      6、Click on Create personal access token.
      7、Save the personal access token somewhere safe. Once you leave or refresh the page, you won't be able to access it again.

意思就是登录公司的git后,在头像--settings--Access tokens 页面,填写name、失效时间以及使用范围,点击创建personal access token。创建成功后,页面会显示access token,这个就是我们需要的值,记住一定要保存下来,否则刷新页面后不再显示。当然也可以删除重新生成

 

 

 

 

更多文章请关注公众号

                                                                           

 

 

                                       

posted on 2021-07-02 09:45  测试步行人  阅读(1357)  评论(0编辑  收藏  举报