无法使用http post调用创建github发行说明

时间:2019-06-05 15:29:55

标签: java json github httpurlconnection release-notes

我正在尝试通过Java REST服务发布github发行说明。通过编写sh脚本和使用curl调用可以达到相同的效果。

我已经通过传递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上发布

错误:{“消息”:“无效的请求。\ n \ n \”标签名\“未提供。”,“ documentation_url”:“ https://developer.github.com/enterprise/2.16/v3/repos/releases/#create-a-release”} < / p>

1 个答案:

答案 0 :(得分:0)

根据GitHub API documentation创建发布,下面是一个示例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());