Example usage for org.apache.http.entity.mime MultipartEntityBuilder setBoundary

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setBoundary

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntityBuilder setBoundary.

Prototype

public MultipartEntityBuilder setBoundary(final String boundary) 

Source Link

Usage

From source file:com.lexmark.saperion.services.PutFileToSaperionECM.java

private static HttpEntity buildMultipart(String base64FileString, String fileName) throws IOException {
    String indexString = "indexName";
    StringBuilder jsonString = new StringBuilder();
    jsonString.append(setECMRequest(indexString, fileName));
    StringBody jsonBody = new StringBody(jsonString.toString(), ContentType.TEXT_PLAIN);

    FormBodyPart jsonBodyPart = new FormBodyPart("body", jsonBody);
    jsonBodyPart.addField("Content-Type", "application/json; charset=UTF-8");
    jsonBodyPart.addField("Content-ID", "body");

    StringBuilder fileBuilder = new StringBuilder();
    fileBuilder.append(base64FileString);
    StringBody fileBody = new StringBody(fileBuilder.toString(), ContentType.TEXT_PLAIN);

    FormBodyPart fileBodyPart = new FormBodyPart("filePart", fileBody);
    fileBodyPart.addField("Content-Type", "image/png");
    fileBodyPart.addField("Content-ID", "<imagefile>");

    MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    multipartBuilder.setMode(HttpMultipartMode.STRICT);
    multipartBuilder.setBoundary("2676ff6efebdb664f8f7ccb34f864e25");
    multipartBuilder.addPart(jsonBodyPart);
    multipartBuilder.addPart(fileBodyPart);

    /*ByteArrayOutputStream out = new ByteArrayOutputStream();
    multipartBuilder.build().writeTo(out);
    out.close();//w w  w.ja  v a  2  s.  co  m
    String s = out.toString("UTF-8");
    System.err.println("output IS "+s);*/

    HttpEntity entity = multipartBuilder.build();
    return entity;

}

From source file:io.andyc.papercut.api.PrintApi.java

/**
 * Uploads the file and finalizes the printing
 *
 * @param printJob    {PrintJob} - the print job
 * @param prevElement {Element} - the previous Jsoup element containing the
 *                    upload file Html/*from w ww.  ja  v  a  2 s.  c  o  m*/
 *
 * @return {boolean} - whether or not the print job completed
 */
static boolean uploadFile(PrintJob printJob, Document prevElement)
        throws PrintingException, UnsupportedMimeTypeException {
    String uploadUrl = printJob.getSession().getDomain().replace("/app", "")
            + PrintApi.getUploadFileUrl(prevElement); // upload directory

    HttpPost post = new HttpPost(uploadUrl);
    CloseableHttpClient client = HttpClientBuilder.create().build();

    // configure multipart post request entity builder
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    // build the file boundary
    String boundary = "-----------------------------" + new Date().getTime();
    entityBuilder.setBoundary(boundary);

    // set the file
    File file = new File(printJob.getFilePath());
    FileBody body = new FileBody(file,
            ContentType.create(ContentTypes.getApplicationType(printJob.getFilePath())), file.getName());
    entityBuilder.addPart("file[]", body);

    // build the post request
    HttpEntity multipart = entityBuilder.build();
    post.setEntity(multipart);

    // set cookie
    post.setHeader("Cookie", printJob.getSession().getSessionKey() + "=" + printJob.getSession().getSession());

    // send
    try {
        CloseableHttpResponse response = client.execute(post);
        return response.getStatusLine().getStatusCode() == 200;
    } catch (IOException e) {
        throw new PrintingException("Error uploading the file");
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java

protected HttpPost buildCatalogRequest(String fullUri) {
    String boundary = "---------------" + UUID.randomUUID().toString();
    HttpPost post = new HttpPost(fullUri);
    post.addHeader("Accept", "application/json");
    post.addHeader("Content-Type",
            org.apache.http.entity.ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundary);
    post.addHeader("sessionId", this.catalogObjectAction.getSessionId());

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", new FileBody(this.catalogObjectAction.getNodeSourceJsonFile()));
    builder.addTextBody(COMMIT_MESSAGE_PARAM, this.catalogObjectAction.getCommitMessage());
    if (!this.catalogObjectAction.isRevised()) {
        builder.addTextBody(NAME_PARAM, this.catalogObjectAction.getNodeSourceName());
        builder.addTextBody(KIND_PARAM, this.catalogObjectAction.getKind());
        builder.addTextBody(OBJECT_CONTENT_TYPE_PARAM, this.catalogObjectAction.getObjectContentType());
    }/*from  w ww.ja v a  2s  .co m*/
    post.setEntity(builder.build());
    return post;
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadVideoRequest.java

/**
 * Create the required multipart entity/*ww  w  .  j a  v  a 2  s  .c  o  m*/
 * @param uploadId Session ID
 * @return Entity to submit to the upload
 * @throws ClientProtocolException
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("media_type", "2");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:com.licryle.httpposter.HttpPoster.java

/**
 * Builds the {@link _ProgressiveEntity} that we will send to the server.
 * Takes for input an {@link HttpConfiguration} that contains the Post
 * variables and File Names to send.//from w  ww.jav a 2 s.c  o m
 *
 * @param mConf Configuration of the POST request to be processed.
 * @return A ProgressiveEntity which progress can be tracked as we send it to
 * the server.
 *
 * @throws IOException When a file in the list of files from
 * {@link HttpConfiguration#getFiles()} cannot be read.
 *
 * @see {@link com.licryle.httpposter.HttpPoster._ProgressiveEntity}
 * @see {@link com.licryle.httpposter.HttpConfiguration}
 */
protected _ProgressiveEntity _buildEntity(HttpConfiguration mConf) throws IOException {
    Log.d("HttpPoster", String.format("_buildEntity: Entering for Instance %d", _iInstanceId));

    /********* Build request content *********/
    MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setBoundary(mConf.getHTTPBoundary());

    int iFileNb = 0;
    Iterator mFiles = mConf.getFiles().iterator();
    while (mFiles.hasNext()) {
        final File mFile = (File) mFiles.next();

        try {
            mBuilder.addBinaryBody("file_" + iFileNb, mFile, ContentType.DEFAULT_BINARY, mFile.getName());
        } catch (Exception e) {
            throw new IOException();
        }

        iFileNb++;
    }

    Iterator mArgs = mConf.getArgs().entrySet().iterator();
    while (mArgs.hasNext()) {
        Map.Entry mPair = (Map.Entry) mArgs.next();

        mBuilder.addTextBody((String) mPair.getKey(), (String) mPair.getValue(),
                ContentType.MULTIPART_FORM_DATA);
    }

    Log.d("HttpPoster", String.format("_buildEntity: Leaving for Instance %d", _iInstanceId));

    return new _ProgressiveEntity(mBuilder.build(), this);
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadAlbumRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException/*  w ww  .jav a  2  s.c  om*/
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(File imageFile, String uploadId)
        throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadStoryPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//from w  ww  .j  a v a 2 s.com
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//w  w  w  .j av a 2 s  . c  o m
 * @throws IOException
 */
protected HttpEntity createMultipartEntity() throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", bufferedImageToByteArray(imageFile), ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:org.apache.stanbol.workflow.jersey.writers.ContentItemWriter.java

@Override
public void writeTo(ContentItem ci, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    //(0) handle default dataType
    Map<String, Object> reqProp = ContentItemHelper.getRequestPropertiesContentPart(ci);
    boolean omitMetadata = isOmitMetadata(reqProp);
    if (!MULTIPART.isCompatible(mediaType)) { //two possible cases
        if (!omitMetadata) { //  (1) just return the RDF data
            //(1.a) Backward support for default dataType if no Accept header is set
            StringBuilder ctb = new StringBuilder();
            if (mediaType.isWildcardType() || TEXT_PLAIN_TYPE.isCompatible(mediaType)
                    || APPLICATION_OCTET_STREAM_TYPE.isCompatible(mediaType)) {
                ctb.append(APPLICATION_LD_JSON);
            } else {
                ctb.append(mediaType.getType()).append('/').append(mediaType.getSubtype());
            }//from w w w. jav  a 2s .  c o  m
            ctb.append(";charset=").append(UTF8.name());
            String contentType = ctb.toString();
            httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
            try {
                serializer.serialize(entityStream, ci.getMetadata(), contentType);
            } catch (UnsupportedSerializationFormatException e) {
                throw new WebApplicationException("The enhancement results "
                        + "cannot be serialized in the requested media type: " + mediaType.toString(),
                        Response.Status.NOT_ACCEPTABLE);
            }
        } else { //  (2) return a single content part
            Entry<UriRef, Blob> contentPart = getBlob(ci, Collections.singleton(mediaType.toString()));
            if (contentPart == null) { //no alternate content with the requeste media type
                throw new WebApplicationException("The requested enhancement chain has not created an "
                        + "version of the parsed content in the reuqest media type " + mediaType.toString(),
                        Response.Status.UNSUPPORTED_MEDIA_TYPE);
            } else { //found -> stream the content to the client
                //NOTE: This assumes that the presence of a charset
                //      implies reading/writing character streams
                String requestedCharset = mediaType.getParameters().get("charset");
                String blobCharset = contentPart.getValue().getParameter().get("charset");
                Charset readerCharset = blobCharset == null ? UTF8 : Charset.forName(blobCharset);
                Charset writerCharset = requestedCharset == null ? null : Charset.forName(requestedCharset);
                if (writerCharset != null && !writerCharset.equals(readerCharset)) {
                    //we need to transcode
                    Reader reader = new InputStreamReader(contentPart.getValue().getStream(), readerCharset);
                    Writer writer = new OutputStreamWriter(entityStream, writerCharset);
                    IOUtils.copy(reader, writer);
                    IOUtils.closeQuietly(reader);
                } else { //no transcoding
                    if (requestedCharset == null && blobCharset != null) {
                        httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE,
                                mediaType.toString() + "; charset=" + blobCharset);
                    }
                    InputStream in = contentPart.getValue().getStream();
                    IOUtils.copy(in, entityStream);
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } else { // multipart mime requested!
        final String charsetName = mediaType.getParameters().get("charset");
        final Charset charset = charsetName != null ? Charset.forName(charsetName) : UTF8;
        MediaType rdfFormat;
        String rdfFormatString = getRdfFormat(reqProp);
        if (rdfFormatString == null || rdfFormatString.isEmpty()) {
            rdfFormat = DEFAULT_RDF_FORMAT;
        } else {
            try {
                rdfFormat = MediaType.valueOf(rdfFormatString);
                if (rdfFormat.getParameters().get("charset") == null) {
                    //use the charset of the default RDF format
                    rdfFormat = new MediaType(rdfFormat.getType(), rdfFormat.getSubtype(),
                            DEFAULT_RDF_FORMAT.getParameters());
                }
            } catch (IllegalArgumentException e) {
                throw new WebApplicationException(
                        "The specified RDF format '" + rdfFormatString
                                + "' (used to serialize all RDF parts of "
                                + "multipart MIME responses) is not a well formated MIME type",
                        Response.Status.BAD_REQUEST);
            }
        }
        //(1) setting the correct header
        String contentType = String.format("%s/%s; charset=%s; boundary=%s", mediaType.getType(),
                mediaType.getSubtype(), charset.toString(), CONTENT_ITEM_BOUNDARY);
        httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setBoundary(CONTENT_ITEM_BOUNDARY);
        //HttpMultipart entity = new HttpMultipart("from-data", charset ,CONTENT_ITEM_BOUNDARY);
        //(2) serialising the metadata
        if (!isOmitMetadata(reqProp)) {
            entityBuilder.addPart("metadata",
                    new ClerezzaContentBody(ci.getUri().getUnicodeString(), ci.getMetadata(), rdfFormat));
            //                entity.addBodyPart(new FormBodyPart("metadata", new ClerezzaContentBody(
            //                    ci.getUri().getUnicodeString(), ci.getMetadata(),
            //                    rdfFormat)));
        }
        //(3) serialising the Content (Bloby)
        //(3.a) Filter based on parameter
        List<Entry<UriRef, Blob>> includedBlobs = filterBlobs(ci, reqProp);
        //(3.b) Serialise the filtered
        if (!includedBlobs.isEmpty()) {
            Map<String, ContentBody> contentParts = new LinkedHashMap<String, ContentBody>();
            for (Entry<UriRef, Blob> entry : includedBlobs) {
                Blob blob = entry.getValue();
                ContentType ct = ContentType.create(blob.getMimeType());
                String cs = blob.getParameter().get("charset");
                if (StringUtils.isNotBlank(cs)) {
                    ct = ct.withCharset(cs);
                }
                contentParts.put(entry.getKey().getUnicodeString(), new InputStreamBody(blob.getStream(), ct));
            }
            //add all the blobs
            entityBuilder.addPart("content",
                    new MultipartContentBody(contentParts, CONTENT_PARTS_BOUNDERY, MULTIPART_ALTERNATE));
        } //else no content to include
        Set<String> includeContentParts = getIncludedContentPartURIs(reqProp);
        if (includeContentParts != null) {
            //(4) serialise the Request Properties
            if (includeContentParts.isEmpty()
                    || includeContentParts.contains(REQUEST_PROPERTIES_URI.getUnicodeString())) {
                JSONObject object;
                try {
                    object = toJson(reqProp);
                } catch (JSONException e) {
                    String message = "Unable to convert Request Properties " + "to JSON (values : " + reqProp
                            + ")!";
                    log.error(message, e);
                    throw new WebApplicationException(message, Response.Status.INTERNAL_SERVER_ERROR);
                }
                entityBuilder.addTextBody(REQUEST_PROPERTIES_URI.getUnicodeString(), object.toString(),
                        ContentType.APPLICATION_JSON.withCharset(UTF8));
            }
            //(5) additional RDF metadata stored in contentParts
            for (Entry<UriRef, TripleCollection> entry : getContentParts(ci, TripleCollection.class)
                    .entrySet()) {
                if (includeContentParts.isEmpty() || includeContentParts.contains(entry.getKey())) {
                    entityBuilder.addPart(entry.getKey().getUnicodeString(), new ClerezzaContentBody(null, //no file name
                            entry.getValue(), rdfFormat));
                } // else ignore this content part
            }
        }
        entityBuilder.build().writeTo(entityStream);
    }

}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Create a multipart upload request.//  www  . j av  a2  s. c o  m
 *
 * @param url the url
 * @param t the object to create
 * @param partName the name of the part
 * @param inputstream the file inputstream
 * @param contentType the type of the file to be attached
 * @return the http request
 * @throws UnsupportedEncodingException the unsupported encoding exception
 */
public <T> Attachment attachFile(String url, T t, String partName, InputStream inputstream, String contentType,
        String attachmentName) throws SmartsheetException {
    Util.throwIfNull(inputstream, contentType);
    Attachment attachment = null;
    final String boundary = "----" + System.currentTimeMillis();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(url));

    try {
        uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);
    builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(t),
            ContentType.APPLICATION_JSON);
    builder.addBinaryBody("file", inputstream, ContentType.create(contentType), attachmentName);
    org.apache.http.HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    try {
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        attachment = this.getSmartsheet().getJsonSerializer()
                .deserializeResult(Attachment.class, responseEntity.getContent()).getResult();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return attachment;
}