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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:com.king.ess.gsa.GSAFeedForm.java

/**
 * It sends XML with feeds to GSA using proper form:
 * /*  w w  w. j a  v a2s . c  om*/
 * @param xmlDocument  GSADocumentFormatter containing XML Document information
 * 
 * @return Was posted Ok?
 */
public boolean sendForm(GSADocumentFormatter xmlDocument) {
    boolean bSent = false;

    HttpClient client = HttpClientBuilder.create().build();

    try {
        HttpPost postPageRequest;
        postPageRequest = new HttpPost(this.gsaServer);
        InputStream is = xmlDocument.writeToInputStream();

        // Add Form parameters
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.addTextBody(FEEDTYPE_PARAM, xmlDocument.getFeedType(), ContentType.TEXT_PLAIN);
        builder.addTextBody(DATASOURCE_PARAM, xmlDocument.getDatasource(), ContentType.TEXT_PLAIN);
        builder.addBinaryBody(XMLFILE_PARAM, is);
        HttpEntity multipartEntity = builder.build();

        postPageRequest.setEntity(multipartEntity);

        HttpResponse postPageResponse = client.execute(postPageRequest);
        int status = postPageResponse.getStatusLine().getStatusCode();

        if (!(bSent = (status == 200)))
            log.error("GitHub API (" + this.gsaServer + ") returned " + status);
        else
            log.info("XML For datasource '" + xmlDocument.getDatasource() + "' and FeedType '"
                    + xmlDocument.getFeedType() + "' was posted successfully to GSA!!");

    } catch (Exception e) {
        log.error("Exception " + e.getMessage() + " in HTTP request " + this.gsaServer);
    }
    return bSent;
}

From source file:org.jboss.as.test.integration.web.multipart.defaultservlet.DefaultServletMultipartConfigTestCase.java

@Test
public void testMultipartRequestToDefaultServlet() throws Exception {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(url.toExternalForm() + "/servlet");
        post.setEntity(MultipartEntityBuilder.create().addTextBody("file", MESSAGE).build());

        HttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        assertEquals(200, statusLine.getStatusCode());

        String result = EntityUtils.toString(entity);
        Assert.assertEquals(MESSAGE, result);
    }/*from w  ww . j  a  va  2 s  . c o m*/
}

From source file:com.m3958.apps.anonymousupload.integration.java.FileUploadTest.java

@Test
public void testPostRename() throws ClientProtocolException, IOException, URISyntaxException {

    File f = new File("README.md");

    Assert.assertTrue(f.exists());/*from   w ww . j  a va  2  s. c o  m*/

    String c = Request.Post(new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).build())
            .body(MultipartEntityBuilder.create()
                    .addBinaryBody("afile", f, ContentType.MULTIPART_FORM_DATA, f.getName())
                    .addTextBody("fn", "abcfn.md").build())
            .execute().returnContent().asString();

    String url = c.trim();
    Assert.assertTrue(url.endsWith("abcfn.md"));

    testComplete();
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);/*from ww  w  .j  a va2s  . co  m*/
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

From source file:org.andstatus.app.net.http.HttpConnectionApacheCommon.java

private void fillMultiPartPost(HttpPost postMethod, JSONObject formParams) throws ConnectionException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    Uri mediaUri = null;//from w w w .  j  ava  2s.com
    String mediaPartName = "";
    Iterator<String> iterator = formParams.keys();
    ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
    while (iterator.hasNext()) {
        String name = iterator.next();
        String value = formParams.optString(name);
        if (HttpConnection.KEY_MEDIA_PART_NAME.equals(name)) {
            mediaPartName = value;
        } else if (HttpConnection.KEY_MEDIA_PART_URI.equals(name)) {
            mediaUri = UriUtils.fromString(value);
        } else {
            // see http://stackoverflow.com/questions/19292169/multipartentitybuilder-and-charset
            builder.addTextBody(name, value, contentType);
        }
    }
    if (!TextUtils.isEmpty(mediaPartName) && !UriUtils.isEmpty(mediaUri)) {
        try {
            InputStream ins = MyContextHolder.get().context().getContentResolver().openInputStream(mediaUri);
            ContentType contentType2 = ContentType.create(MyContentType.uri2MimeType(mediaUri, null));
            builder.addBinaryBody(mediaPartName, ins, contentType2, mediaUri.getPath());
        } catch (SecurityException e) {
            throw new ConnectionException("mediaUri='" + mediaUri + "'", e);
        } catch (FileNotFoundException e) {
            throw new ConnectionException("mediaUri='" + mediaUri + "'", e);
        }
    }
    postMethod.setEntity(builder.build());
}

From source file:nya.miku.wishmaster.http.ExtendedMultipartBuilder.java

public ExtendedMultipartBuilder() {
    builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .setBoundary(generateBoundary());
}

From source file:com.cognifide.qa.bb.aem.content.ContentInstaller.java

/**
 * This method uploads, installs and replicates the package indicated by the name
 * provided as the method's parameter. For each of these actions activateAemPackage constructs
 * and sends a POST request to AEM instance. If any of the POST requests lead to NOK response,
 * activateAemPackage will throw an exception.
 * <br>/*from w  w w. j  a va 2 s.  c o  m*/
 * Method will look for content in the location indicated by the content.path property.
 * The content path defaults to "src/main/content".
 *
 * @param packageName Name of the package to be activated.
 * @throws IOException Thrown when AEM instance returns NOK response.
 */
public void activateAemPackage(String packageName) throws IOException {
    HttpPost upload = builder.createUploadRequest();
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addBinaryBody("package", new File(CONTENT_PATH, packageName), ContentType.DEFAULT_BINARY,
            packageName);
    entityBuilder.addTextBody("force", "true");
    upload.setEntity(entityBuilder.build());
    JsonObject result = sender.sendCrxRequest(upload);
    String path = result.get("path").getAsString();

    HttpPost install = builder.createInstallRequest(path);
    sender.sendCrxRequest(install);

    HttpPost replicate = builder.createReplicateRequest(path);

    sender.sendCrxRequest(replicate);
}

From source file:put.semantic.fcanew.script.HandcraftedScript.java

@Override
public void submitLog(File logfile) {
    try {/*from  ww  w.j a va2s .  c om*/
        HttpPost post = new HttpPost("http://semantic.cs.put.poznan.pl/fca/submit.php");
        HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("file", logfile).build();
        post.setEntity(entity);
        try (CloseableHttpClient client = HttpClients.createDefault();
                CloseableHttpResponse response = client.execute(post)) {
            System.err.println(response);
            System.err.println(EntityUtils.toString(response.getEntity()));
        }
    } catch (Throwable ex) {
        Logger.getLogger(HandcraftedScript.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.flowable.admin.service.engine.FormDeploymentService.java

public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream)
        throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, "form-repository/deployments"));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(name, IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, name)
            .build();/*from www  .  j a va  2s . c om*/
    post.setEntity(reqEntity);
    return clientUtil.executeRequest(post, serverConfig, 201);
}

From source file:com.movilizer.mds.webservice.models.MovilizerUploadForm.java

private MultipartEntityBuilder getForm(long systemId, String password, String pool, String key, String lang,
        String suffix, String ack) {
    MultipartEntityBuilder form = MultipartEntityBuilder.create()
            .addTextBody("systemId", String.valueOf(systemId), ContentType.TEXT_PLAIN)
            .addTextBody("password", password, ContentType.TEXT_PLAIN)
            .addTextBody("pool", pool, ContentType.TEXT_PLAIN).addTextBody("key", key, ContentType.TEXT_PLAIN)
            .addTextBody("suffix", suffix, ContentType.TEXT_PLAIN);
    if (lang != null) {
        form.addTextBody("lang", lang, ContentType.TEXT_PLAIN);
    }/*from w  w w.  j  ava  2  s.c o  m*/
    if (ack != null) {
        form.addTextBody("ack", suffix, ContentType.TEXT_PLAIN);
    }
    return form;
}