I'm trying to post an attachment o JIRA using the latest REST API.
Here's my code:
public boolean addAttachmentToIssue(String issueKey, String path){
String auth = new
String(org.apache.commons.codec.binary.Base64.encodeBase64((user+":"+pass).getBytes()));
Client client = Client.create();
WebResource webResource = client.resource(baseURL+"issue/"+issueKey+"/attachments");
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
File f = new File(path);
if(f.exists() && f.isFile()){
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
return false;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
}
fis.close();
bos.close();
} catch (IOException ex) {
try {
fis.close();
bos.close();
} catch (IOException e) {
return false;
}
return false;
}
byte[] bytes = bos.toByteArray();
FormDataBodyPart bodyPart = new FormDataBodyPart("file", new ByteArrayInputStream(bytes), MediaType.APPLICATION_OCTET_STREAM_TYPE);
formDataMultiPart.bodyPart(bodyPart);
}else{
return false;
}
ClientResponse response = null;
response = webResource.header("Authorization", "Basic " + auth).header("X-Atlassian-Token", "nocheck").type(MediaType.MULTIPART_FORM_DATA).accept("application/json").post(ClientResponse.class, formDataMultiPart);
System.out.println(response);
int statusCode = response.getStatus();
System.out.println(statusCode);
String resp = response.getEntity(String.class);
System.out.println(resp);
return true;
}
However, i get the following response:
POST http://localhost:8082/rest/api/2/issue/TEST-2/attachments returned a response status of 404 Not Found
404
XSRF check failed
An Issue with key TEST-2 does exist in the my local JIRA instance and I can add the attachment "by hand" in the Jira app itself.
I know that i must add a header of type "X-Atlassian-Token:nocheck" to prevent XSRF, but, by the output, I must be doing something wrong..
What confuses me even further is that a 404 is thrown after the XSRF check failed.
I've scavenged google for answers with no success
Can anyone hazard a guess to what I'm doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…