“ 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,這個就是我們需要的值,記住一定要保存下來,否則刷新頁面后不再顯示。當然也可以刪除重新生成
更多文章請關注公眾號