1

我正在尝试通过 Java REST 服务发布 github 发行说明。通过编写 sh 脚本和使用 curl post call 实现了相同的目的。

我已经编写了代码来通过传递 JsonObject 数据使用 HttpUrlConnection 进行 POST 调用。

    String postUrl = "host_name/api/v3/repos/"+ userName + "/" + project_name
        + "/releases";

    URL url = new URL(postUrl);

    JSONObject values = new JSONObject();
    JSONObject data = new JSONObject();

    values.put("tag_name", "TEST_TAG1");
    values.put("target_commitish", "master");
    values.put("name", "1.0");
    values.put("body", "TEST Description");
    values.put("draft", false);
    values.put("prerelease", false);
    data.put("data", values);

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", "token goes here");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "application/vnd.github.v3+json");
    con.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(data.toString());
    wr.flush();
    wr.close();

预期结果:发行说明应该在 github 上发布

错误:{"message":"无效请求。\n\n\"tag_name\" 未提供。","documentation_url":" https://developer.github.com/enterprise/2.16/v3/repos/发布/#create-a-release "}

4

1 回答 1

0

根据用于创建发布的GitHub API 文档,下面是一个示例 requestBody

{
  "tag_name": "v1.0.0",
  "target_commitish": "master",
  "name": "v1.0.0",
  "body": "Description of the release",
  "draft": false,
  "prerelease": false
}

但是在您的代码中,您已经形成了以下格式的 requestBody

{
  "data": {
    "tag_name": "v1.0.0",
    "target_commitish": "master",
    "name": "v1.0.0",
    "body": "Description of the release",
    "draft": false,
    "prerelease": false
  }
}

由于请求所需的所有字段都JSONObject values在您的代码中,因此直接传递它而不是使用JSONObject data.

所以本质上,替换wr.write(data.toString());wr.write(values.toString());

于 2019-06-05T16:10:54.233 回答