You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GitHub API创建远程仓库时遇Redirection Blocked异常求助

我来帮你搞定这个JGit推送时碰到的重定向阻止问题~先理清楚你的问题场景和异常:

你的代码(核心片段)

// 省略本地仓库创建逻辑
try{
    RemoteAddCommand remoteAddCommand = git.remoteAdd();
    remoteAddCommand.setName("origin");
    remoteAddCommand.setUri(new URIish("URL")); // 此处URL未指向具体仓库
    remoteAddCommand.call();
    git.commit().setMessage("try").call();

    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("user", "pwd"));
    pushCommand.setRemote("https://github.com/org").call(); // 仅指向组织地址
    git.push().setForce(true).call();
} catch(Exception e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}

触发的异常

org.eclipse.jgit.api.errors.TransportException: http://github.com/org/: Redirection blocked: redirect https://github.com/org/ -> https://github.com/login?return_to=https%3A%2F%2Fgithub.corp.ebay.com%2Fvtrmigrated%2Finfo%2Frefs%3Fservice%3Dgit-receive-pack not allowed

问题根源分析

从异常和代码来看,导致重定向被阻止的核心原因有三个:

  1. 远程仓库URL错误:你设置的地址是https://github.com/org(仅指向组织主页),而非具体的Git仓库地址(格式应为https://github.com/org/your-repo.git)。GitHub会将这种无效的仓库请求重定向到登录或组织页面,而JGit默认会拦截这类非预期重定向。
  2. 认证方式过时:GitHub早已废弃了密码登录Git操作的方式,使用用户名+密码会被拒绝,进而触发登录重定向。
  3. 缺少远程仓库创建步骤:JGit本身只能操作本地仓库和执行推送/拉取,无法直接创建GitHub远程仓库。你跳过了创建远程仓库的步骤直接推送,导致GitHub返回重定向。

分步解决方案

1. 先通过GitHub API创建远程仓库

你需要先调用GitHub的REST API创建目标仓库,再用JGit推送。以下是用Java原生HttpURLConnection实现的示例:

private static void createGitHubRepo(String patToken, String orgName, String repoName) throws IOException {
    URL apiUrl = new URL("https://api.github.com/orgs/" + orgName + "/repos");
    HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "token " + patToken);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setDoOutput(true);

    // 构造创建仓库的请求体
    String requestBody = "{\"name\": \"" + repoName + "\", \"private\": false}";
    try(OutputStream os = conn.getOutputStream()) {
        byte[] input = requestBody.getBytes("utf-8");
        os.write(input, 0, input.length);
    }

    int responseCode = conn.getResponseCode();
    if (responseCode >= 200 && responseCode < 300) {
        System.out.println("远程仓库创建成功:" + repoName);
    } else {
        throw new IOException("创建仓库失败,响应码:" + responseCode);
    }
}

注意:这里需要使用GitHub个人访问令牌(PAT),在GitHub设置中生成时要勾选repo权限(私有仓库需额外权限)。

2. 修正JGit代码的URL与认证逻辑

将远程仓库地址改为具体的仓库URL,并用PAT替换密码:

public static void main(String[] args) throws IOException, GitAPIException, URISyntaxException {
    String patToken = "你的GitHub个人访问令牌";
    String orgName = "你的组织名称";
    String repoName = "目标仓库名称";
    
    // 第一步:创建远程仓库
    createGitHubRepo(patToken, orgName, repoName);

    // 初始化本地仓库(复用你原有的createSampleGitRepo逻辑)
    File repoDir = createSampleGitRepo();
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try (Repository repository = builder.setGitDir(repoDir)
            .readEnvironment()
            .findGitDir()
            .build()) {
        Git git = new Git(repository);
        try{
            // 设置正确的远程仓库URL
            String remoteRepoUrl = "https://github.com/" + orgName + "/" + repoName + ".git";
            RemoteAddCommand remoteAddCommand = git.remoteAdd();
            remoteAddCommand.setName("origin");
            remoteAddCommand.setUri(new URIish(remoteRepoUrl));
            remoteAddCommand.call();

            // 推送代码(指定分支,避免默认推送所有分支的问题)
            PushCommand pushCommand = git.push();
            pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("你的GitHub用户名", patToken));
            pushCommand.setRemote("origin");
            pushCommand.setRefSpecs(new RefSpec("master:master")); // 推送本地master到远程master
            pushCommand.call();

            System.out.println("代码推送成功!");
        } catch(Exception e) {
            e.printStackTrace();
            System.out.println("错误信息:" + e.getMessage());
        } finally {
            git.close();
        }
    }
    // 可选:清理临时本地仓库
    // FileUtils.deleteDirectory(repoDir.getParentFile());
}

3. (可选)临时允许JGit重定向(不推荐)

如果只是临时调试需要允许重定向,可以通过TransportConfigCallback配置,但这只是治标,优先解决前面的核心问题:

pushCommand.setTransportConfigCallback(transport -> {
    if (transport instanceof HttpTransport) {
        ((HttpTransport) transport).setFollowRedirects(true);
    }
});

关键注意事项

  • 确保PAT令牌有足够权限:至少需要repo权限(私有仓库需额外配置)。
  • 远程仓库URL必须精确到具体仓库,不能只指向组织或用户主页。
  • JGit仅负责本地Git操作和推送/拉取,创建远程仓库必须调用GitHub官方API。

内容的提问来源于stack exchange,提问作者Maria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:48:24