使用org.kohsuke.github Java API无法向已有Gist中新增文件问题求助
问题核心原因
你编写的Gist文件更新操作没有触发实际的API请求。org.kohsuke.github库中GHGist.update()返回的GHGistUpdater对象的所有配置方法(包括addFile、deleteFile、updateFile、修改描述等)都只是本地构建请求参数,必须调用链式方法末尾的done()才会将请求真正提交到GitHub服务器,这就是你代码无报错也无实际效果的原因。
各类文件操作的正确实现
新增Gist文件
public static void addFileToGist(String filename, String contents, String gistId) { GHGist gist = getGist(gistId); try{ gist.update() .addFile(filename,contents) .done(); // 必须添加这行触发请求提交 CustomAlert.showInfo("File Added"); } catch (IOException e) {e.printStackTrace();} }
更新已有文件内容
public static void updateGistFile(String fileName, String newContent, String gistId) { GHGist gist = getGist(gistId); try{ gist.update() .updateFile(fileName, newContent) .done(); } catch (IOException e) {e.printStackTrace();} }
删除Gist内指定文件
public static void deleteGistFile(String fileName, String gistId) { GHGist gist = getGist(gistId); try{ gist.update() .deleteFile(fileName) .done(); } catch (IOException e) {e.printStackTrace();} }
批量操作多个文件
如果需要同时对同一个Gist下多个文件执行增删改操作,可以在同一个update()链式配置中完成所有参数设置,最后只调用一次done()即可,无需多次发起请求:
gist.update() .addFile("newFile.md", "内容") .updateFile("oldFile.md", "新内容") .deleteFile("deprecatedFile.md") .setDescription("更新了Gist描述") .done();
简化Gist文件内容获取方式
你之前自行调用HTTP连接器拉取文件内容的方式可以简化,调用GHGist.read()方法即可拉取Gist的完整详情,直接获取到文件内容,无需手动构造请求:
public static String getGistFileContent(String fileName, String gistId) { String fileContents = ""; try { GHGist gist = gitHub.getGist(gistId).read(); fileContents = gist.getFile(fileName).getContent(); } catch (IOException e) {e.printStackTrace();} return fileContents; }
注意事项
- 操作Gist的OAuth令牌必须勾选
gist权限,权限不足会导致操作无返回或失败,可以到GitHub个人设置的令牌管理页确认权限配置。 - 所有更新类操作都需要调用
done()提交请求,查询类操作无需此步骤。
内容的提问来源于stack exchange,提问作者Michael Sims
相关产品推荐
相关产品推荐

