【问题标题】:How to connect to github using Java Program如何使用Java程序连接到github
【发布时间】:2018-06-25 06:17:07
【问题描述】:

有人可以帮我如何连接到 Github 以及如何使用 Java 程序上传文档吗?

我想连接到 Github,连接后我想使用 Java 程序将文档上传到 github。

非常感谢, 拉朱

【问题讨论】:

  • 我们需要更多细节。如果你想连接 github,你可能需要使用 github api。尝试点击以下 url api.github.com/repos/vmg/redcarpet 你应该得到一些 JSON 数据。使用像 servlet 或 spring mvc 这样的框架来调用 github api。请阅读文档并提供更多信息,例如您是否正在开发 Web 应用程序/控制台应用程序/桌面应用程序?
  • @djam 我没有开发任何应用程序..我的要求只是使用 Java 将文件上传到 GitHub,我尝试使用 Github API 但仍然无法进行身份验证..

标签: java github


【解决方案1】:

最简单的解决方案是使用 Github 库之一。如果你对 Java 感兴趣,那么你需要使用this one

首先,您需要使用您的 Github 帐户进行身份验证。这是自述文件中的示例:

//Basic authentication
GitHubClient client = new GitHubClient();
client.setCredentials("user", "passw0rd");
//OAuth2 token authentication
GitHubClient client = new GitHubClient();
client.setOAuth2Token("SlAV32hkKG");

那么这取决于您希望如何将文档上传到 Github。最简单的方法是创建一个Gist。为此,请使用以下代码:

GistFile file = new GistFile();
file.setContent("System.out.println(\"Hello World\");");
Gist gist = new Gist();
gist.setDescription("Prints a string to standard out");
gist.setFiles(Collections.singletonMap("Hello.java", file));
GistService service = new GistService();
service.getClient().setCredentials("user", "passw0rd");
gist = service.createGist(gist); //returns the created gist

注意 Gist 是公开的,因此如果您想将其设为私有,您需要明确地进行操作

【讨论】:

  • 嗨 Anatolli,我无法在 Github API 中找到 GitHubClient 类 ..
  • 嗨。这里是github.com/eclipse/egit-github/blob/master/…。请确保您正确添加了库。你使用 Maven 之类的构建工具吗?
  • 是的,它在 org.eclipse.egit.github 库中,而不是在 GitHub API 中——我正在使用 Gradle,现在如果我想检查是否能够向 Github 进行身份验证,该怎么做-- 我写了 GitHubClient 客户端 = new GitHubClient(); client.setCredentials("user", "passw0rd");但是如何验证 authentcaton 是否成功?我需要在这里写任何断言语句吗?你能详细帮忙吗..
  • 您需要将 service.createGist(gist) 调用包装在 try catch 块中。基本上有两个您感兴趣的异常:IOException 和 RequestException。 IOException 表示存在一些与传输相关的交互错误。库中定义了 RequestException 来指示 api 交互错误。检查此github.com/eclipse/egit-github/blob/master/…。请求异常里面有状态码。对于身份验证错误,通常是 401
猜你喜欢
  • 2017-12-08
  • 2011-03-23
  • 2019-08-04
  • 2011-07-30
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多