【发布时间】:2018-12-23 00:31:51
【问题描述】:
我在存储库中使用 Github 的 API 到 update a file。以下命令适用于curl(已替换令牌字段):
curl -i -X PUT -H 'Authorization: token 2****************0' -d '{"path": "test6.txt", "message": "test", "sha":"863ba79d293acda68556bbddc1f97a29cb7b98bf","content": "dGVzdDM0Cg==", "
branch": "master"}' https://api.github.com/repos/pedro-roberto/test2/contents/test6.txt
sha更新并从这里获取https://api.github.com/repos/pedro-roberto/test2/contents/test6.txt
content参数是我要更新的文件的base64编码(命令行中base64 file.txt,Java中byte[] encodedBytes = Base64.encodeBase64(JsonArray_TO_UPLOAD.toString().getBytes()); String jsonInBase64 = new String(encodedBytes);)
我曾尝试在 Java 中执行此请求,但我以响应代码 400:Bad request 失败
尝试 1
Map<String, String> parameters = new HashMap<>();
parameters.put("path", "test6.txt" );
parameters.put("message","test");
parameters.put("sha", "863ba79d293acda68556bbddc1f97a29cb7b98bf" );
parameters.put("content", "dGVzdDM0Cg==");
parameters.put("branch", "master");
URL url = new URL(https://api.github.com/repos/pedro-roberto/test2/contents/test6.txt);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("PUT");
con.setRequestProperty("Authorization","token 2********************0");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
尝试 2
List<NameValuePair> params = new ArrayList<NameValuePair>();;
params.add(new BasicNameValuePair("path", "test6.txt");
params.add(new BasicNameValuePair("message","test"));
params.add(new BasicNameValuePair("sha", "863ba79d293acda68556bbddc1f97a29cb7b98bf"));
params.add(new BasicNameValuePair("content", "dGVzdDM0Cg=="));
params.add(new BasicNameValuePair("branch", "master"));
HttpClient httpclient = HttpClients.createDefault();
HttpPut con2 = new HttpPut(link);
con2.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
con2.addHeader("Authorization","token 2*****************0");
HttpResponse response = httpclient.execute(con2);
HttpEntity entity = response.getEntity();
不知道该怎么做才能完成这项工作。请帮忙!
编辑: 我认为问题与我构建查询字符串的方式有关。我试图让它在 Postman 中工作,它只有在我停止使用参数并使用 body/raw/JSON 并将参数作为 JSON 发送时才起作用(这里的问题:400 Problems parsing JSON - GitHub API and POSTMAN using OAuth)。不知道如何将其集成到 Java 中...
【问题讨论】:
-
您可以使用众多开源 JSON 库之一。
-
经过一番挖掘后设法找到了解决方案。用解决方案回答了我自己的问题。谢谢。
标签: java httprequest httpurlconnection apache-httpclient-4.x github-api