-1

I'm trying to translate this CURL to Java. I'm having a hard time, especially with multipart uploads.

curl -X POST \
-H "Content-Type: multipart/form-data" \
-H "Authorization: Bearer ${AUTH_TOKEN}" \
-F attached_file=@test.png \
-F from_comment=False \
-F object_id=1 \
-F project=1 \
-s http://localhost:8000/api/v1/tasks/attachments
Mike G
  • 4,232
  • 9
  • 40
  • 66
Marko
  • 1
  • 3

1 Answers1

-1

JavaMail has MimeMultipart and MimeBodyPart classes for this:

MimeBodyPart attachedFile = new MimeBodyPart();
attachedFile.setDisposition("form-data; name=\"attached_file\"");
attachedFile.attachFile("test.png");

MimeBodyPart fromComment = new MimeBodyPart();
fromComment.setDisposition("form-data; name=\"from_comment\"");
fromComment.setText("False");

MimeBodyPart objectID = new MimeBodyPart();
objectID.setDisposition("form-data; name=\"object_id\"");
objectID.setText("1");

MimeBodyPart project = new MimeBodyPart();
project.setDisposition("form-data; name=\"project\"");
project.setText("1");

MimeMultipart multipart = new MimeMultipart("form-data",
    attachedFile, fromComment, objectID, project);

URL url = new URL("http://localhost:8000/api/v1/tasks/attachments");
HttpURLConnection connection = (HttpURLConnection) url.getConnection();

connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("Authorization", "Bearer " + authToken);

connection.setRequestMethod("POST");
connection.setDoOutput(true);

try (OutputStream body = connection.getOutputStream()) {
    multipart.writeTo(body);
}

int responseCode = connection.getResposneCode();
if (responseCode >= 400 || responseCode < 0) {
    System.err.println("Response returned HTTP " + responseCode);

    InputStream response = connection.getErrorStream();
    if (response != null) {
        response.transferTo(System.err);
        response.close();
    }
}
VGR
  • 40,506
  • 4
  • 48
  • 63
  • JavaMail is for processing email, it is not intended for uploading files. – Mark Rotteveel May 09 '19 at 18:12
  • @MarkRotteveel JavaMail also contains a complete implementation of MIME content. – VGR May 09 '19 at 18:14
  • 1
    Yes, and its geared towards transferring data for mail-related protocols. Using it for http may be possible, but it is unwieldy and likely inefficient. Better to use a specialized HTTP library. – Mark Rotteveel May 09 '19 at 18:18