Hi all!
I'm trying to upload a pdf file to one of my Jira issues using Java. I tried older solutions posted on this forum, but they doesn't seem to work. Here is what I have now:
public CloseableHttpResponse addAttachment(String baseUrl, String issueKey, String filePath) throws IOException{
try (CloseableHttpClient client = HttpClientBuilder.create().build();) {
HttpPost httpPost = new HttpPost(baseUrl+"/"+issueKey+"/attachments");
httpPost.setHeader(new BasicHeader("Authorization", "Bearer " + apiKey));
httpPost.setHeader("X-Atlassian-Token", "no-check");
httpPost.setHeader("Content-Type", "multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p");
File file = new File(filePath);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = client.execute(httpPost);
return response;
}
}
My problem is that it sends the request and responds with 200, but with a body of: [], and nothing is uploaded. Everything works fine with Postman, so it must be something with my code.
Someone please help me fix it.
Thanks,
Ákos
Community moderators have prevented the ability to post new answers.
I couldn't solve the problem, but found a workaround. If I use a curl command from the code then it works.
For anyone, who has the same problem here is my code:
public String addAttachment(String issueKey, String filePath) throws IOException {
//Command to execute
String[] command = {
"curl",
"-X", "POST",
"-H", "Authorization: Bearer " + apiKey,
"-H", "X-Atlassian-Token: no-check",
"-F", "file=@"+filePath,
baseUrl + "/issue/" + issueKey + "/attachments"
};
// Create ProcessBuilder
ProcessBuilder processBuilder = new ProcessBuilder(command);
// Start the process
Process process = processBuilder.start();
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String respond = "";
String line;
while ((line = reader.readLine()) != null) {
respond = respond.concat(line);
}
return respond;
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.