【问题标题】:downloading jar file from github?从github下载jar文件?
【发布时间】:2020-09-12 18:51:05
【问题描述】:

我已将一个 10 meg 的 jar 文件提交到 git 存储库,我想使用 Java 下载该文件。该文件可以直接从 github 下载,但是当我尝试从命令行卷曲它时(作为实验——我肯定需要从程序中执行此操作)有两件事: 1.它似乎进行得太快了——我不认为我得到了真正的罐子。 2. 我想我正在获取 HTML。我知道源文件的“原始”,但 Github 上显然没有为二进制文件提供原始选项。

在程序中,我能够对源代码执行的操作是一次读取下载 1 行并附加这些行,最终重新创建文件。不确定这将如何处理大型 jar 文件。

编辑:有一个“查看原始”选项将 ?raw=true 附加到 URL,但在 Java 中不起作用,当我从命令行尝试时,它似乎不起作用 - 仍然获取 html 并下载速度太快了。

编辑:这是 github 中存在的 jar 文件的命令行 curl: curl -u testuser https://github.com/test/test-api/blob/master/testjarfile.jar?raw=true

以上产生的结果,但我不认为这是我们需要的。这是Java代码:

URL url;
    String username="testuser";
    String password= "testpass";
    StringBuilder file = new StringBuilder();//deliberately not thread-safe
    try {
        url = new URL("https://github.com/test/test-api/blob/master/testjarfile.jar?raw=true");
        URLConnection uc;
        uc = url.openConnection();

        uc.setRequestProperty("X-Requested-With", "Curl");
        String userpass = username + ":" + password;
        String basicAuth = "Basic " + new String(Base64.getEncoder().encodeToString(userpass.getBytes()));//needs Base64 encoder, apache.commons.codec
        uc.setRequestProperty("Authorization", basicAuth);

        BufferedReader reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) 
            file.append(line+"\n");
        System.out.println(file);

这个 Java 代码给出了找不到文件。请注意,从 github 网页上,似乎确实下载了 jarfile。还要注意我猜想的“raw = true”会导致下载原始文件,而不是html等。

【问题讨论】:

  • 请发布您当前的代码以获取上下文。出于您的目的,您绝对不想逐行阅读。我假设您正在使用BufferedReader 来完成此操作。见baeldung.com/java-download-file。我怀疑 GitHub 需要标头来下载发布文件,但您可能需要对打开与标头的连接进行一些研究。

标签: java git curl


【解决方案1】:

首先尝试“How can I download a single raw file from a private github repo using the command line?”中描述的 curl 命令,从命令行检查 curl 本身是否有效。

curl -H 'Authorization: token YOUR_TOKEN' \
  -H 'Accept: application/vnd.github.v4.raw' \
  -O \
  -L https://api.github.com/repos/INSERT_OWNER_HERE/INSERT_REPO_HERE/contents/PATH/TO/FILE

然后使用rockswang/java-curlcurl 调用转换为Java。

【讨论】:

  • 如果没有令牌,只有用户名和密码怎么办?
  • @relseabe 首先,如果 repo 是公开的,则根本不需要 Authorization 标头。其次,如果没有,您可以自己生成一个 OAuth 令牌:gist.github.com/joyrexus/85bf6b02979d8a7b0308#oauth
  • so密码,就算你有,也不用?
  • @relseabe 否,不适用于授权标头
  • api.github.com 总是正确的吗?当我尝试下载 jar 时收到 404。但是,在 github 上找到该文件的 url 没有提到 api.github.com,而只是 github.com
猜你喜欢
  • 2017-05-09
  • 2011-06-04
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 2016-01-09
  • 2013-11-13
  • 2020-07-29
相关资源
最近更新 更多