Home > Enterprise >  Get Content of agit respository
Get Content of agit respository

Time:08-04

I need a way of getting the content of the GitHub repository in java. For example I wanna download this file: Example Repository

With a method like this:

public String getRepository(String url) {
    String result = // do somthing;
    return result;
}

When We call it with

  getRepository("github.com/Call-for-Code/Project-Sample/blob/main/sample-static-web/css/styles.css");

It shoukd return

"/*\n* Copyright 2020-2021 Daniel Krook\n* \n* Licensed under the Apache License, Version 2.0 (the "License"); \n* you may not use this file except in compliance with the License. \n* You may obtain a copy of the License at\n* \n* http://www.apache.org/licenses/LICENSE-2.0\n* \n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an "AS IS" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/"

CodePudding user response:

If you replace github.com by raw.githubusercontent.com and remove /blob from the URL (which you can do it dynamically of course), then you automatically get the URL of the "raw" view of the same file.

Hence, a simple HTTP GET call on that URL will contain the content of the file in the body:

@Test
public void test() throws IOException, InterruptedException {
    String url = "https://github.com/Call-for-Code/Project-Sample/blob/main/sample-static-web/css/styles.css";
    System.out.println(getContent(url));
}

private String getContent(String url) throws IOException, InterruptedException {
    HttpClient client = HttpClient.newHttpClient();
    String rawUrl = url.replace("github.com", "raw.githubusercontent.com").replace("/blob", "");
    HttpRequest request = HttpRequest.newBuilder().uri(URI.create(rawUrl)).build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    return response.body();
}

Of course, if the repository is private, you'll need to add an authentication to your HTTP request.

P.s. in my example I'm using Java 11's java.net.* Http client, but of course you can use whatever HTTP client you prefer (the concept is always the same).

  • Related