Example usage for org.apache.http.entity ContentType MULTIPART_FORM_DATA

List of usage examples for org.apache.http.entity ContentType MULTIPART_FORM_DATA

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType MULTIPART_FORM_DATA.

Prototype

ContentType MULTIPART_FORM_DATA

To view the source code for org.apache.http.entity ContentType MULTIPART_FORM_DATA.

Click Source Link

Usage

From source file:com.ritesh.idea.plugin.util.HttpRequestBuilder.java

private HttpRequestBase getHttpRequest() throws URISyntaxException, UnsupportedEncodingException {
    if (!route.isEmpty()) {
        String path = urlBuilder.getPath() + route;
        path = path.replace("//", "/");
        urlBuilder.setPath(path);//from   w  ww.j ava 2s  .c  om
    }
    request.setURI(urlBuilder.build());
    if (request instanceof HttpPost) {
        if (fileParam != null) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (NameValuePair formParam : formParams) {
                builder.addTextBody(formParam.getName(), formParam.getValue());
            }
            HttpEntity entity = builder
                    .addBinaryBody(fileParam, fileBytes, ContentType.MULTIPART_FORM_DATA, fileName).build();
            ((HttpPost) request).setEntity(entity);
        } else if (!formParams.isEmpty()) {
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(formParams));
        }
    } else if (request instanceof HttpPut) {
        if (!formParams.isEmpty()) {
            ((HttpPut) request).setEntity(new UrlEncodedFormEntity(formParams));
        }
    }
    return request;

}

From source file:org.biopax.validator.BiopaxValidatorClient.java

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //ww w .  java2 s  .  c  om
 * and prints the results to the output stream.
 * 
 * @param autofix true/false (experimental)
 * @param profile validation profile name
 * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true)
 * @param biopaxUrl check the BioPAX at the URL
 * @param biopaxFiles an array of BioPAX files to validate
 * @param out
 * @throws IOException
 */
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs,
        String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException {
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.setCharset(Charset.forName("UTF-8"));

    if (autofix)
        meb.addTextBody("autofix", "true");

    //TODO add extra options (normalizer.fixDisplayName, normalizer.xmlBase)?

    if (profile != null && !profile.isEmpty())
        meb.addTextBody("profile", profile);
    if (retFormat != null)
        meb.addTextBody("retDesired", retFormat.toString().toLowerCase());
    if (filterBy != null)
        meb.addTextBody("filter", filterBy.toString());
    if (maxErrs != null && maxErrs > 0)
        meb.addTextBody("maxErrors", maxErrs.toString());
    if (biopaxFiles != null && biopaxFiles.length > 0)
        for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type
            meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName());
    else if (biopaxUrl != null) {
        meb.addTextBody("url", biopaxUrl);
    } else {
        log.error("Nothing to do (no BioPAX data specified)!");
        return;
    }

    HttpEntity httpEntity = meb.build();
    //       if(log.isDebugEnabled()) httpEntity.writeTo(System.err);
    String content = Executor.newInstance().execute(Request.Post(url).body(httpEntity)).returnContent()
            .asString();

    //save: append to the output stream (file)
    BufferedReader res = new BufferedReader(new StringReader(content));
    String line;
    PrintWriter writer = new PrintWriter(out);
    while ((line = res.readLine()) != null) {
        writer.println(line);
    }
    writer.flush();
    res.close();
}

From source file:ua.pp.msk.maven.MavenHttpClient.java

private int execute(File file) throws ArtifactPromotingException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    int status = -1;
    try {//from  w  w w  . ja v  a2 s.c  o m
        getLog().debug("Connecting to URL: " + url);
        HttpPost post = new HttpPost(url);

        post.setHeader("User-Agent", userAgent);

        if (username != null && username.length() != 0 && password != null) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            post.addHeader(new BasicScheme().authenticate(creds, post, null));
        }
        if (file == null) {
            if (!urlParams.isEmpty()) {
                post.setEntity(new UrlEncodedFormEntity(urlParams));
            }
        } else {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            if (!urlParams.isEmpty()) {
                for (NameValuePair nvp : urlParams) {
                    builder.addPart(nvp.getName(),
                            new StringBody(nvp.getValue(), ContentType.MULTIPART_FORM_DATA));
                }
            }
            FileBody fb = new FileBody(file);
            // Not used because of form submission
            // builder.addBinaryBody("file", file,
            // ContentType.DEFAULT_BINARY, file.getName());
            builder.addPart("file", fb);
            HttpEntity sendEntity = builder.build();
            post.setEntity(sendEntity);
        }

        CloseableHttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        StatusLine statusLine = response.getStatusLine();
        status = statusLine.getStatusCode();
        getLog().info(
                "Response status code: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        // Perhaps I need to parse html
        // String html = EntityUtils.toString(entity);

    } catch (AuthenticationException ex) {
        throw new ArtifactPromotingException(ex);
    } catch (UnsupportedEncodingException ex) {
        throw new ArtifactPromotingException(ex);
    } catch (IOException ex) {
        throw new ArtifactPromotingException(ex);
    } finally {
        try {
            client.close();
        } catch (IOException ex) {
            throw new ArtifactPromotingException("Cannot close http client", ex);
        }
    }
    return status;
}

From source file:com.microsoft.cognitive.speakerrecognition.SpeakerRestClientHelper.java

/**
 * Adds a stream to an HTTP entity/*from   www  .  j av  a2 s .c o m*/
 *
 * @param someStream Input stream to be added to an HTTP entity
 * @param fieldName A description of the entity content
 * @param fileName Name of the file attached as an entity
 * @return HTTP entity
 * @throws IOException Signals a failure while reading the input stream
 */
HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int bytesRead;
    byte[] bytes = new byte[1024];
    while ((bytesRead = someStream.read(bytes)) > 0) {
        byteArrayOutputStream.write(bytes, 0, bytesRead);
    }
    byte[] data = byteArrayOutputStream.toByteArray();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.setStrictMode();
    builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName);
    return builder.build();
}

From source file:org.rapidoid.http.HttpClientUtil.java

private static NByteArrayEntity paramsBody(Map<String, Object> data, Map<String, List<Upload>> files) {
    data = U.safe(data);/*  ww w  .  ja  va2 s .  co  m*/
    files = U.safe(files);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    for (Map.Entry<String, List<Upload>> entry : files.entrySet()) {
        for (Upload file : entry.getValue()) {
            builder = builder.addBinaryBody(entry.getKey(), file.content(), ContentType.DEFAULT_BINARY,
                    file.filename());
        }
    }

    for (Map.Entry<String, Object> entry : data.entrySet()) {
        String name = entry.getKey();
        String value = String.valueOf(entry.getValue());
        builder = builder.addTextBody(name, value, ContentType.DEFAULT_TEXT);
    }

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        builder.build().writeTo(stream);
    } catch (IOException e) {
        throw U.rte(e);
    }

    byte[] bytes = stream.toByteArray();
    return new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);
}

From source file:objective.taskboard.it.TemplateIT.java

private HttpResponse uploadTemplate(File file) throws URISyntaxException, IOException {
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody templateName = new StringBody(file.getName(), ContentType.MULTIPART_FORM_DATA);
    StringBody roles = new StringBody("Role", ContentType.MULTIPART_FORM_DATA);
    builder.addPart("file", fileBody);
    builder.addPart("name", templateName);
    builder.addPart("roles", roles);
    HttpEntity entity = builder.build();

    HttpPost post = new HttpPost();
    post.setURI(new URI("http://localhost:8900/api/templates"));
    post.setHeaders(session);//from w  ww .  ja v  a2s. co  m
    post.setEntity(entity);

    return client.execute(post);
}

From source file:org.biopax.paxtools.client.BiopaxValidatorClient.java

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //w ww . j  ava2s.co  m
 * and prints the results to the output stream.
 * 
 * @param autofix true/false (experimental)
 * @param profile validation profile name
 * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true)
* @param filterBy filter validation issues by the error/warning level
* @param maxErrs errors threshold - max no. critical errors to collect before quitting
*                (warnings not counted; null/0/negative value means unlimited)
 * @param biopaxUrl check the BioPAX at the URL
 * @param biopaxFiles an array of BioPAX files to validate
 * @param out validation report data output stream
 * @throws IOException when there is an I/O error
 */
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs,
        String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException {
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.setCharset(Charset.forName("UTF-8"));

    if (autofix)
        meb.addTextBody("autofix", "true");
    //TODO add extra options (normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource, normalizer.xmlBase)?
    if (profile != null && !profile.isEmpty())
        meb.addTextBody("profile", profile);
    if (retFormat != null)
        meb.addTextBody("retDesired", retFormat.toString().toLowerCase());
    if (filterBy != null)
        meb.addTextBody("filter", filterBy.toString());
    if (maxErrs != null && maxErrs > 0)
        meb.addTextBody("maxErrors", maxErrs.toString());
    if (biopaxFiles != null && biopaxFiles.length > 0)
        for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type
            meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName());
    else if (biopaxUrl != null) {
        meb.addTextBody("url", biopaxUrl);
    } else {
        log.error("Nothing to do (no BioPAX data specified)!");
        return;
    }

    //execute the query and get results as string
    HttpEntity httpEntity = meb.build();
    //       httpEntity.writeTo(System.err);
    String content = Executor.newInstance()//Executor.newInstance(httpClient)
            .execute(Request.Post(url).body(httpEntity)).returnContent().asString();

    //save: append to the output stream (file)
    BufferedReader res = new BufferedReader(new StringReader(content));
    String line;
    PrintWriter writer = new PrintWriter(out);
    while ((line = res.readLine()) != null) {
        writer.println(line);
    }
    writer.flush();
    res.close();
}

From source file:com.tur0kk.facebook.FacebookClient.java

public String publishPicture(String msg, Image image, String placeId) throws IOException {
    OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node
    request.addHeader("Authorization", "Bearer " + accesTokenString); // authentificate

    // check input to avoid error responses
    if (msg != null && image != null) {
        // facebook requires multipart post structure
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("message", msg); // description

        if (placeId != null && !"".equals(placeId)) {
            builder.addTextBody("place", placeId); // add link to FabLab site if property is set in preferences
        }//from w w  w. ja  v  a2 s  .  c o  m

        // convert image to bytearray and append to multipart
        BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(image, 0, 0, null);
        bGr.dispose();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bimage, "png", baos);
        builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png");

        // generate multipart byte stream and add to payload of post package
        HttpEntity multipart = builder.build();
        ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream(
                (int) multipart.getContentLength());
        multipart.writeTo(multipartOutStream);
        request.addPayload(multipartOutStream.toByteArray());

        // set header of post package
        Header contentType = multipart.getContentType();
        request.addHeader(contentType.getName(), contentType.getValue());

        // send and response answer
        Response response = request.send();
        return response.getBody();
    } else {
        throw new RuntimeException("message and image needed");
    }
}

From source file:com.hp.ov.sdk.rest.http.core.client.HttpRestClient.java

public String sendMultipartPostRequest(RestParams restParams, File file) throws SDKBadRequestException {
    if (restParams.getType() != HttpMethodType.POST) {
        throw new SDKBadRequestException(SDKErrorEnum.badRequestError, null, null, null, SdkConstants.APPLIANCE,
                null);/*from   www  .j av a2s . c o m*/
    }

    try {
        HttpPost post = new HttpPost(buildURI(restParams));

        HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("file", file)
                .setContentType(ContentType.MULTIPART_FORM_DATA).build();

        post.setEntity(entity);
        post.setConfig(createRequestTimeoutConfiguration());

        post.setHeader("uploadfilename", file.getName());
        post.setHeader("Auth", restParams.getSessionId());
        post.setHeader("X-Api-Version", String.valueOf(restParams.getApiVersion().getValue()));
        post.setHeader("Accept", restParams.getHeaders().get("Accept"));
        post.setHeader("accept-language", restParams.getHeaders().get("accept-language"));

        return getResponse(post, restParams, false);
    } catch (IllegalArgumentException e) {
        throw new SDKBadRequestException(SDKErrorEnum.badRequestError, null, null, null, SdkConstants.APPLIANCE,
                e);
    }
}