简体   繁体   中英

How to access the repository names in GitHub with Java?

I have an application, where I have many different repositories in the GitHub. In my application, I need to get the Name of each repository. I searched a lot in the Inte.net and of course in Stack Overflow to access the GitHub repos but I found no suitable solution for me.

Hopefully somebody have a good idea or has experience with it.

@Value("${github.githubUrl}")
String url;

public void getEach() {
    try {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(this.url);
        request.addHeader("content-type", "application/json");
        HttpResponse result = httpClient.execute(request);
        String json = EntityUtils.toString(result.getEntity(), "UTF-8");

        System.out.println("Json kommmt=============================  "+ json);

        JsonElement jelement = new JsonParser().parse(json);
        JsonArray jarr = jelement.getAsJsonArray();
        for (int i = 0; i < jarr.size(); i++) {
            JsonObject jo = (JsonObject) jarr.get(i);
            String fullName = jo.get("full_name").toString();
            fullName = fullName.substring(1, fullName.length()-1);
            System.out.println("fullname kommt ================  " + fullName);
        }

    } catch (IOException ex) {
        System.out.println(ex.getStackTrace());
    }
}

I could see an existing code here.

https://github.com/hub4j/github-api/blob/9ab6d570193dc381a0cda7cc4991f471499dcf24/src/main/java/org/kohsuke/github/GHPerson.java#L70-L89

public PagedIterable<GHRepository> listRepositories(final int pageSize) {
    return new PagedIterable<GHRepository>() {
        public PagedIterator<GHRepository> _iterator(int pageSize) {
            return new PagedIterator<GHRepository>(root.retrieve().asIterator("/users/" + login + "/repos?per_page=" + pageSize, GHRepository[].class, pageSize)) {
                @Override
                protected void wrapUp(GHRepository[] page) {
                    for (GHRepository c : page)
                        c.wrap(root);
                }
            };
        }
    };
}

As per github documentation , the list of repositories would be like this:

List organization repositories
Lists repositories for the specified organization.
GET /orgs/{org}/repos

Note:
Or if it's just a requirement to list the repos, try this -

curl "https://api.github.com/users/$GHUSER/repos?access_token=$GITHUB_API_TOKEN" | grep -w clone_url

Steps 1,2,3 will help you to create token as in https://crunchify.com/how-to-access-github-content-with-basic-oauth-authentication-in-java-httpclient-or-urlconnection-method/

And if really rely on java, you can try the curl in java! (you should find a way to grep)

URL url = new URL("https://api.github.com/users/" + GHUSER + "/repos?access_token=" + GITHUB_API_TOKEN); //pagesize too

try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
    for (String line; (line = reader.readLine()) != null;) {
        System.out.println(line);
    }
}

Check out https://github.com/hub4j/github-api , it has all you need. This is a code sample that I assume does what you want - fetches the list of repos within a specified organization.

import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import org.kohsuke.github.PagedIterable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;

@SpringBootApplication
public class GhScanner implements CommandLineRunner {

    @Value("${github.oauthToken}")
    private String oauthToken;

    public static void main(String[] args) {
        SpringApplication.run(GhScanner.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        if (args.length < 1) {
            throw new IllegalArgumentException("Expected organization name as the 1st argument");
        }
        var githubOrganization = args[0];
        System.out.printf("Fetching repos for organization '%s':%n", githubOrganization);
        var iterator = getRepos(githubOrganization).iterator();
        while (iterator.hasNext()) {
            iterator.nextPage().stream()
                    .map(GHRepository::getName)
                    .forEach(System.out::println);
        }
    }

    private PagedIterable<GHRepository> getRepos(String githubOrganization) throws IOException {
        GitHub gitHub = GitHub.connectUsingOAuth(oauthToken);
        return gitHub.getOrganization(githubOrganization).listRepositories();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM