简体   繁体   中英

Reading git Repo using C# gives error 404

I'm trying to read private git repo "I'm watching, not mine" I've been trying many codes online but every time I get error 404 not found, the fact, I can for sure open the repo in the browser.

Still can't figure out the issue is it the Token? how to get?

Here's the code Change the information, like the owner, repo name and token to get it to work

using GitHubRepoGrabber.GithubClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace GitHubRepoGrabber{
class Program
{
    static void Main(string[] args)
    {

        //try 1
        var task = Github.getRepo("owner", "repo", "token");
        task.Wait();
        var dir = task.Result;

        //try 2
        Task.Factory.StartNew(async () =>
        {
            var repoOwner = "owner";
            var repoName = "name";
            var path = "path";

            var httpClientResults = await ListContents(repoOwner, repoName, path);
            PrintResults("From HttpClient", httpClientResults);

            var octokitResults = await ListContentsOctokit(repoOwner, repoName, path);
            PrintResults("From Octokit", octokitResults);

        }).Wait();
        Console.ReadKey();
    }
    static async Task<IEnumerable<string>> ListContents(string repoOwner, string repoName, string path)
    {
        using (var client = GetGithubHttpClient())
        {
            var resp = await client.GetAsync($"repos/{repoOwner}/{repoName}/contents/{path}");
            var bodyString = await resp.Content.ReadAsStringAsync();
            var bodyJson = JToken.Parse(bodyString);
            return bodyJson.SelectTokens("$.[*].name").Select(token => token.Value<string>());
        }
    }

    static async Task<IEnumerable<string>> ListContentsOctokit(string repoOwner, string repoName, string path)
    {
        var client = new GitHubClient(new Octokit.ProductHeaderValue("Github-API-Test"));
        // client.Credentials = ... // Set credentials here, otherwise harsh rate limits apply.

        var contents = await client.Repository.Content.GetAllContents(repoOwner, repoName, path);
        return contents.Select(content => content.Name);
    }

    private static HttpClient GetGithubHttpClient()
    {
        return new HttpClient
        {
            BaseAddress = new Uri("https://api.github.com"),
            DefaultRequestHeaders =
        {
            // NOTE: You'll have to set up Authentication tokens in real use scenario
            // NOTE: as without it you're subject to harsh rate limits.
            {"User-Agent", "Github-API-Test"}
        }
        };
    }

    static void PrintResults(string source, IEnumerable<string> files)
    {
        Console.WriteLine(source);
        foreach (var file in files)
        {
            Console.WriteLine($" -{file}");
        }
    }   }namespace GithubClient
{
    //JSON parsing methods
    struct LinkFields
    {
        public String self;
    }
    struct FileInfo
    {
        public String name;
        public String type;
        public String download_url;
        public LinkFields _links;
    }

    //Structs used to hold file data
    public struct FileData
    {
        public String name;
        public String contents;
    }
    public struct Directory
    {
        public String name;
        public List<Directory> subDirs;
        public List<FileData> files;
    }

    //Github classes
    public class Github
    {
        //Get all files from a repo
        public static async Task<Directory> getRepo(string owner, string name, string access_token)
        {
            HttpClient client = new HttpClient();
            Directory root = await readDirectory("root", client, String.Format("https://api.github.com/repos/{0}/{1}/contents/", owner, name), access_token);
            client.Dispose();
            return root;
        }

        //recursively get the contents of all files and subdirectories within a directory 
        private static async Task<Directory> readDirectory(String name, HttpClient client, string uri, string access_token)
        {
            //get the directory contents
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
            request.Headers.Add("Authorization",
                "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", access_token, "x-oauth-basic"))));
            request.Headers.Add("User-Agent", "lk-github-client");

            //parse result
            HttpResponseMessage response = await client.SendAsync(request);
            String jsonStr = await response.Content.ReadAsStringAsync(); ;
            response.Dispose();
            FileInfo[] dirContents = JsonConvert.DeserializeObject<FileInfo[]>(jsonStr);

            //read in data
            Directory result;
            result.name = name;
            result.subDirs = new List<Directory>();
            result.files = new List<FileData>();
            foreach (FileInfo file in dirContents)
            {
                if (file.type == "dir")
                { //read in the subdirectory
                    Directory sub = await readDirectory(file.name, client, file._links.self, access_token);
                    result.subDirs.Add(sub);
                }
                else
                { //get the file contents;
                    HttpRequestMessage downLoadUrl = new HttpRequestMessage(HttpMethod.Get, file.download_url);
                    downLoadUrl.Headers.Add("Authorization",
                        "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", access_token, "x-oauth-basic"))));
                    request.Headers.Add("User-Agent", "lk-github-client");

                    HttpResponseMessage contentResponse = await client.SendAsync(downLoadUrl);
                    String content = await contentResponse.Content.ReadAsStringAsync();
                    contentResponse.Dispose();

                    FileData data;
                    data.name = file.name;
                    data.contents = content;

                    result.files.Add(data);
                }
            }
            return result;
        }
    }
}

}

问题是令牌没有足够的权限,一旦我给了正确的权限,它就可以完美运行!

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