如何使用java或curl实用工具将文档(图像等)附加到现有的工作项azuredevops。我试着用curl实用程序和java代码来实现它,但它不起作用。java代码示例:
try {
// urlOfAttachment - url of attachment to devops azure, got with this method:
// https://stackoverflow.com/questions/62034062/upload-an-attachment-to-azure-devops-rest-api
String jsonInputString = "[{\"op\":\"add\",\"path\":\"/relations/-\",\"value\":" +
"{\"rel\":\"HelloFile.txt\",\"url\":\"" + urlOfAttachment + "\"," +
"\"attributes\":{\"comment\":\"Spec for the work\"}}}]";
URL url = new URL(
"https://dev.azure.com/[organization]/[project]/_apis/wit" +
"/workItems/2?api-version=5.1");
// PAT - token
HttpURLConnection con = apiConnectionAttachToTicket(PAT, url, jsonInputString);
try (BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("There would be response");
System.out.println(response.toString());
System.out.println("End of response");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
}
public static HttpURLConnection apiConnectionAttachToTicket(String PAT, URL url, String jsonInputString) {
HttpURLConnection con = null;
try {
String AuthStr = ":" + PAT;
Base64 base64 = new Base64();
String encodedPAT = new String(base64.encode(AuthStr.getBytes()));
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", "Basic " + encodedPAT);
con.setRequestProperty("Content-Type", "application/json-patch+json");
con.setDoOutput(true);
System.out.println("URL - " + url.toString());
System.out.println("PAT - " + encodedPAT);
con.setDoInput(true);
con.setRequestProperty("X-HTTP-Method-Override", "PATCH");
con.setRequestMethod("POST");
con.setRequestProperty("data", jsonInputString);
System.out.println("Exit from function");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return con;
}
此方法返回411错误。我认为是因为它没有将方法类型设置为patch,而是使用post。但是devopsazure不支持post(我在尝试使用curl时得到了它)。当我使用curl时,它返回消息:“您必须在请求主体中传递一个有效的文档”。但我检查了好几次,似乎是对的。curl请求示例:
curl -L -D- --user [mail]@gmail.com:[token] --header "Content-Type:application/json-patch+json" --request POST -d '{"op":"add","path":"/relations/-","value":"AttachedFile","url":"https://dev.azure.com/[orgranization]/280b4f85-e666-4069-8b3b-2116ff5d9b7a/_apis/wit/attachments/ff9f26e7-6595-462d-833c-40f9771f3035?fileName=HelloFile.txt","attributes":{"comment":"Spec for the work"}}}' https://dev.azure.com/[organization]/[project]/_apis/wit/workitems/2?api-version=6.0
有什么想法吗?
1条答案
按热度按时间myzjeezk1#
您可以首先尝试使用postman来测试json格式。检查是否可以将restapi与json主体一起使用来上载附件。
如果未指定注解,则该注解链接不正确。i、 e.本规范:
应该是: