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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:com.codedx.burp.ExportActionListener.java

private HttpResponse sendData(File data, String urlStr) throws IOException {
    CloseableHttpClient client = burpExtender.getHttpClient();
    if (client == null)
        return null;

    HttpPost post = new HttpPost(urlStr);
    post.setHeader("API-Key", burpExtender.getApiKey());

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", new FileBody(data));

    HttpEntity entity = builder.build();
    post.setEntity(entity);//from   ww  w  .  j a  v  a2 s .  co  m

    HttpResponse response = client.execute(post);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        EntityUtils.consume(resEntity);
    }
    client.close();

    return response;
}

From source file:io.undertow.servlet.test.security.basic.ServletCertAndDigestAuthTestCase.java

@Test
public void testMultipartRequest() throws Exception {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 2000; i++) {
        sb.append("0123456789");
    }//w  ww.  java 2  s.  c  om

    try (TestHttpClient client = new TestHttpClient()) {
        // create POST request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("part1", new ByteArrayBody(sb.toString().getBytes(), "file.txt"));
        builder.addPart("part2", new StringBody("0123456789", ContentType.TEXT_HTML));
        HttpEntity entity = builder.build();

        client.setSSLContext(clientSSLContext);
        String url = DefaultServer.getDefaultServerSSLAddress() + BASE_PATH + "multipart";
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        post.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64
                .encodeString(("user1" + ":" + "password1").getBytes(StandardCharsets.UTF_8), false));

        HttpResponse result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    }
}

From source file:com.cognifide.aet.common.TestSuiteRunner.java

private SuiteExecutionResult startSuiteExecution(File testSuite) throws IOException {
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("suite", testSuite,
            ContentType.APPLICATION_XML, testSuite.getName());
    if (domain != null) {
        entityBuilder.addTextBody("domain", domain);
    }//w  ww  .ja v  a2  s.com
    HttpEntity entity = entityBuilder.build();
    return Request.Post(getSuiteUrl()).body(entity).connectTimeout(timeout).socketTimeout(timeout).execute()
            .handleResponse(suiteExecutionResponseHandler);
}

From source file:de.siegmar.securetransfer.controller.MvcTest.java

@Test
public void invalidFormSubmit() throws Exception {
    // message missing
    final String boundary = "------TestBoundary" + UUID.randomUUID();
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary(boundary);

    mockMvc.perform(post("/send").content(ByteStreams.toByteArray(builder.build().getContent()))
            .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary))
            .andExpect(status().isOk()).andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(model().hasErrors());
}

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

/**
 * Adds a stream to an HTTP entity/*from   ww  w .j a  v  a 2  s  . c om*/
 *
 * @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.uberfire.provisioning.wildfly.runtime.provider.extras.Wildfly10RemoteClient.java

public int deploy(String user, String password, String host, int port, String filePath) {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password));

    CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost post = new HttpPost("http://" + host + ":" + port + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    File file = new File(filePath);
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {//w  ww  .  j  a va  2  s .  c o m
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    //entity.writeTo(System.out);
    post.setEntity(entity);

    try {
        HttpResponse response = httpclient.execute(post);

        out.println(">>> Deploying Response Entity: " + response.getEntity());
        out.println(">>> Deploying Response Satus: " + response.getStatusLine().getStatusCode());
        return response.getStatusLine().getStatusCode();
    } catch (IOException ex) {
        ex.printStackTrace();
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }
    return -1;
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.Bean.AbstractMultiPartRequest.java

public HttpEntity generateMulipartEnitity() {
    MultipartEntityBuilder reqBuilder = MultipartEntityBuilder.create();
    parameterMap.clear();//  w w w  . java 2  s  .  c o  m
    init();
    Iterator<String> irt = parameterMap.keySet().iterator();
    String key;
    ContentBody value;
    while (irt.hasNext()) {
        key = irt.next();
        value = parameterMap.get(key);
        reqBuilder.addPart(key, value);
    }
    return reqBuilder.build();
}

From source file:securitytools.veracode.http.request.UploadFileRequest.java

public UploadFileRequest(String applicationId, File file, String sandboxId) {
    super("/api/4.0/uploadfile.do");

    if (applicationId == null) {
        throw new IllegalArgumentException("Application id cannot be null.");
    }/*  w w w .  j  av a2  s .  c o m*/
    if (!file.canRead()) {
        throw new IllegalArgumentException("Cannot read file.");
    }

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addPart("app_id", new StringBody(applicationId, ContentType.TEXT_PLAIN));

    if (sandboxId != null) {
        entityBuilder.addPart("sandbox_id", new StringBody(sandboxId, ContentType.TEXT_PLAIN));
    }

    entityBuilder.addPart("file", new FileBody(file));

    setEntity(entityBuilder.build());
}

From source file:com.jaeksoft.searchlib.scheduler.task.TaskUploadMonitor.java

@Override
public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog)
        throws SearchLibException {
    String url = properties.getValue(propUrl);
    URI uri;/*from ww w .j a  v  a2  s .com*/
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    }
    String login = properties.getValue(propLogin);
    String password = properties.getValue(propPassword);
    String instanceId = properties.getValue(propInstanceId);

    CredentialItem credentialItem = null;
    if (!StringUtils.isEmpty(login) && !StringUtils.isEmpty(password))
        credentialItem = new CredentialItem(CredentialType.BASIC_DIGEST, null, login, password, null, null);
    HttpDownloader downloader = client.getWebCrawlMaster().getNewHttpDownloader(true);
    try {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("instanceId",
                new StringBody(instanceId, ContentType.TEXT_PLAIN));

        new Monitor().writeToPost(entityBuilder);
        DownloadItem downloadItem = downloader.post(uri, credentialItem, null, null, entityBuilder.build());
        if (downloadItem.getStatusCode() != 200)
            throw new SearchLibException(
                    "Wrong code status:" + downloadItem.getStatusCode() + " " + downloadItem.getReasonPhrase());
        taskLog.setInfo("Monitoring data uploaded");
    } catch (ClientProtocolException e) {
        throw new SearchLibException(e);
    } catch (IOException e) {
        throw new SearchLibException(e);
    } catch (IllegalStateException e) {
        throw new SearchLibException(e);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    } finally {
        downloader.release();
    }

}

From source file:com.releasequeue.server.ReleaseQueueServer.java

@Override
public HttpResponse uploadPackage(FilePath packagePath, String distribution, String component)
        throws MalformedURLException, IOException {
    String repoType = FilenameUtils.getExtension(packagePath.toString());

    String uploadPath = String.format("%s/%s/repositories/%s/packages?distribution=%s&component=%s",
            this.basePath, this.userName, repoType, distribution, component);
    URL uploadPackageUrl = new URL(this.serverUrl, uploadPath);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(uploadPackageUrl.toString());
    setAuthHeader(uploadFile);//www.  ja  va 2s .com

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(packagePath.toString()), ContentType.APPLICATION_OCTET_STREAM,
            packagePath.getName());
    HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    HttpResponse response = httpClient.execute(uploadFile);
    return response;
}