如何用Java进行CURL调用?

时间:2019-05-09 13:53:05

标签: java multipartform-data

我正在尝试将此CURL转换为Java。我很难过,尤其是分段上传。

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

1 个答案:

答案 0 :(得分:-1)

JavaMail具有MimeMultipartMimeBodyPart类:

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();
    }
}