Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Unable to add attachment in Jira via rest api

David Whitlock May 2, 2023

I am attempting to upload a file to a Jira Issue via the rest api. I get a return code of 415 when I do. Below is my code snippet, any recommendations would be forthcoming:

 

String url = "https://" + serverName + "/rest/api/2/issue/" + issuenbr + "/attachments";
logger.debug("URL IS " + url);
boolean attachmentAdded = false;
BasicHeader contenttype = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
BasicHeader jiraheader = new BasicHeader("X-Atlassian-Token", "no-check");
List<BasicHeader> headers = new ArrayList<BasicHeader>();
headers.add(contenttype);
headers.add(jiraheader);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(sys_username, sys_password)
);

try (CloseableHttpClient httpclient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.setDefaultHeaders(headers)
.build();) {
File file = new File(fileuri);
String message = file.getName();

// build multipart upload request,modes: HttpMultipartMode.BROWSER_COMPATIBLE
HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532)
.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName())
.addTextBody("text", message, ContentType.DEFAULT_BINARY).build();

// build http request and assign multipart upload data
HttpUriRequest request = RequestBuilder.post(url).setEntity(data).build();

CloseableHttpResponse response = httpclient.execute(request); {

// 401 if wrong user/password
System.out.println(response.getStatusLine().getStatusCode());

HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println("Response::" + result);
}

}

1 answer

1 accepted

0 votes
Answer accepted
David Whitlock May 10, 2023

I implemented the authorization header improperly, this works:

 

BasicHeader authHeader = new BasicHeader("Authorization", getBasicAuthenticationHeader(sys_username, sys_password));
List<BasicHeader> headers = new ArrayList<BasicHeader>();
headers.add(jiraheader);
headers. Add(authHeader);

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
SERVER
VERSION
8.20.10
TAGS
AUG Leaders

Atlassian Community Events