Add Attachment using REST API in Java

gopi krishna October 22, 2020

I'm working on a Java project to add attachments to an existing jira issue.

I'm using below Jira resource, which works fine from postman.

POST /rest/api/2/issue/{issueIdOrKey}/attachments

But when I try to achieve the same thing using java it's not working as expected. Below is the piece of code I'm using in Java. Actually, this rest call is going fine with no errors, but the attachment is NOT appearing in Jira UI.

Below java response is NOT matching with what I'm getting in postman.

 

Java code :

public void addAttachment(String filename , String issueId) throws Exception
{

RestTemplate restTemplate = new RestTemplate();
headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setBasicAuth("username", "password");
headers.set("X-Atlassian-Token", "no-check");

File file = new File(filename);


MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();

body.add("files", file);



HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);

String addAttachUrl = "https://jirainstance.com/rest/api/2/issue/"+issueId+"/attachments";
ResponseEntity<String> output = restTemplate.postForEntity(addAttachUrl, requestEntity, String.class);
LOG.info(output.getBody());

}

 

RESPONSE : 

<200,[],[Date:"Thu, 22 Oct 2020 20:09:48 GMT", Server:"Apache", X-AREQUESTID:"969x3612218x1", X-XSS-Protection:"1; mode=block", X-Content-Type-Options:"nosniff", X-Frame-Options:"SAMEORIGIN", Content-Security-Policy:"frame-ancestors 'self'", X-ASEN:"SEN-2785822", X-Seraph-LoginReason:"OK", X-ASESSIONID:"4mlpm2", X-AUSERNAME:"206410801", Cache-Control:"no-cache, no-store, no-transform", Content-Type:"application/json;charset=UTF-8", Set-Cookie:"JSESSIONID=3AF3DF62B49EC36313A4FCFE3CE69F78; Path=/; HttpOnly", "atlassian.xsrf.token=BXAJ-8ECA-NR3P-YUW5_9cd43f77837537f6850277c8a77cbc424bfda405_lin; Path=/", Vary:"Accept-Encoding", Keep-Alive:"timeout=15, max=100", Connection:"Keep-Alive", Transfer-Encoding:"chunked"]>

 

Thanks,

 

 

2 answers

1 accepted

1 vote
Answer accepted
gopi krishna October 22, 2020

I found the solution. Looks like I"m not passing the file content along with the request here.

Thats the reason I was getting 200 response but no attachment in Jira.

Kian Stack Mumo Systems
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
October 23, 2020

Gopi, if you post the code that did eventually work here, others might derive value from that if they run into a similar problem!

AbhijitM August 6, 2021

@gopi krishna ,

I am facing similar issue. Can you please share the code which worked for you. That will help me resolve the issue.

I am facing issue when importing the test results from testng-results.xml. Though other execute details gets updated on the XRay test execution but the attachment doesn't. i have tried quite a few solution but didn't work.

Probably your solution can help me to do some trick here.

Your help on this will be appreciated.

Stefan Koenhorst
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
September 28, 2021

Found a solution?

gopi krishna September 28, 2021
// Below approach is tried and tested method.
public  void addAttachmentToJira(String filename, String jiraissue) throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    headers.setBasicAuth(jiraUser, jiraPwd);
    headers.set("X-Atlassian-Token""no-check");
    File sampleFile = new File(filename);
  
  
    MultiValueMap<StringStringfileMap = new LinkedMultiValueMap<>();
    ContentDisposition contentDisposition = ContentDisposition
            .builder("form-data")
            .name("file")
            .filename(sampleFile.getName())
            .build();
    fileMap.add(HttpHeaders.CONTENT_DISPOSITIONcontentDisposition.toString());
    byte[] fileContent = Files.readAllBytes(sampleFile.toPath());
    HttpEntity<byte[]> fileEntity = new HttpEntity<>(fileContent, fileMap);
    MultiValueMap<StringObjectbody = new LinkedMultiValueMap<>();
    body.add("file", fileEntity);

    HttpEntity<MultiValueMap<StringObject>> requestEntity =
            new HttpEntity<>(body, headers);
    try {
        String addAttachUrl = "https://yourjirainstance.com/rest/api/2/issue/"+issueId+"/attachments";
        ResponseEntity<Stringresponse = restTemplate.exchange(
                addAttachUrl,
                HttpMethod.POST,
                requestEntity,
                String.class);
    } catch (HttpClientErrorException e) {
        e.printStackTrace();
    }
}
Like # people like this
Angela Brown November 28, 2021

Thank you! This was a huge help :)

0 votes
Shubam Sharma
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
April 26, 2022

scala solution:

import org.apache.http.entity.mime.content.FileBody
import org.apache.http.entity.mime.{HttpMultipartMode, MultipartEntityBuilder}
import org.apache.http.impl.client.HttpClients
import org.apache.http.client.methods.{HttpPost}
@throws(classOf[Exception])
def addAttachmentToJiraTicket(jiraTicketId: String, attachmentPath: Path): Unit ={
val credential = new UsernamePasswordCredentials(AppConfig.instance.jiraMailId, AppConfig.instance.jiraToken)
val post = new HttpPost(myServer + "/rest/api/2/issue/" + jiraTicketId + "/attachments")
post.addHeader(new BasicScheme().authenticate(credential, post, null))
post.addHeader("X-Atlassian-Token", "no-check")

val entity = MultipartEntityBuilder.create()
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new FileBody(attachmentPath.toFile,ContentType.APPLICATION_OCTET_STREAM))

post.setEntity(entity.build())
val response = HttpClients.createDefault().execute(post)
val statusCode = response.getStatusLine.getStatusCode
if (statusCode != 200) {
throw new Exception(s"Invalid response status code:$statusCode")
}
}

Suggest an answer

Log in or Sign up to answer