How to access project information and content through Gitlab's API

Gitlab provides many ways to use API to access its information. This article will mainly explain how to use the "Access Tokens" to access the information in its API.

table of Contents

1. Preliminary preparation

2. Actual use of Java access code

3. API parameters and explanation


1. Preliminary preparation

Log in to gitlab, find the "Access Tokens" in the left sidebar in the following figure 1 in the personal settings, then fill in the information in the figure according to your own needs, and finally click the create button to get the key information in figure 2 and save it.

2. Code combat

The pom file package is

<dependency>
     <groupId>org.gitlab</groupId>
     <artifactId>java-gitlab-api</artifactId>
     <version>4.1.1</version>
</dependency>
public static void main(String[] args) {
        GitlabAPI gitlabAPI = GitlabAPI.connect("url地址", "刚刚获得的accessToken");
        try {
            GitlabProject gitlabProject = gitlabAPI.getProject("你的namespace", "你的projectName");
            List<GitlabBranch> gitlabBranchList = gitlabAPI.getBranches(gitlabProject);
            for(int i = 0;i<gitlabBranchList.size();i++){
                System.out.println(gitlabBranchList.get(i).getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
}

The final output is:

3. Analysis of key methods of GitlabAPI source code

Check the source code, there are a lot of get methods, you can get the information content you want. Examples of several key commonly used

getRepositoryFile ()

First look at the source code. It is very clear and clear that this method is used to obtain all the files of the project. The file object of the entire project is obtained by passing in the project object, path, and branch name.

public GitlabRepositoryFile getRepositoryFile(GitlabProject project, String path, String ref) throws IOException {
        Query query = new Query()
                .append("ref", ref);

        String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository/files/" + sanitizePath(path) + query.toString();
        return retrieve().to(tailUrl, GitlabRepositoryFile.class);
    }

After the file object is obtained, the content inside is obtained through the getContent() method in the GitlabRepositoryFile entity class, but in order to finally realize the view of the code, the following decryption algorithm must be done.

new String(decoder.decode(gitlabRepositoryFile.getContent()), "UTF-8");

 

Guess you like

Origin blog.csdn.net/Aaron_ch/article/details/112342058