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.codota.uploader.Uploader.java

private void uploadFile(File file, String uploadUrl) throws IOException {
    HttpPut putRequest = new HttpPut(uploadUrl);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("code", new FileBody(file));
    final HttpEntity entity = builder.build();
    putRequest.setEntity(entity);//w  ww  .j  av a 2 s . c om

    putRequest.setHeader("enctype", "multipart/form-data");
    putRequest.setHeader("authorization", "bearer " + token);
    httpClient.execute(putRequest, new UploadResponseHandler());
}

From source file:erainformatica.utility.JSONHelper.java

public static TelegramRequestResult<JSONObject> readJsonFromUrl(String url, InputFile file) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(url);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
    builder.addBinaryBody(file.getName(), file.getFile_content(), ContentType.APPLICATION_OCTET_STREAM,
            file.getName() + "." + file.getExtension());
    HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);// w ww.j  a va  2  s.c om

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(uploadFile);
    } catch (IOException ex) {
        Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
    HttpEntity responseEntity = response.getEntity();

    try {
        return readJsonFromInputStream(responseEntity.getContent());
    } catch (Exception ex) {
        return new TelegramRequestResult<>(false, ex.toString(), null);
    }

}

From source file:io.fabric8.maven.support.Apps.java

/**
 * Posts a file to the git repository//from  w  w w  . j av  a 2 s.c o m
 */
public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl,
        String branch, String path, Logger logger) throws URISyntaxException, IOException {
    HttpClientBuilder builder = HttpClients.custom();
    if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443),
                new UsernamePasswordCredentials(user, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }

    CloseableHttpClient client = builder.build();
    try {

        String url = consoleUrl;
        if (!url.endsWith("/")) {
            url += "/";
        }
        url += "git/";
        url += branch;
        if (!path.startsWith("/")) {
            url += "/";
        }
        url += path;

        logger.info("Posting App Zip " + file.getName() + " to " + url);
        URI buildUrl = new URI(url);
        HttpPost post = new HttpPost(buildUrl);

        // use multi part entity format
        FileBody zip = new FileBody(file);
        HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build();
        post.setEntity(entity);
        // post.setEntity(new FileEntity(file));

        HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post);
        logger.info("Response: " + response);
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode < 200 || statusCode >= 300) {
                throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response);
            }
        }
        return response;
    } finally {
        Closeables.closeQuietly(client);
    }
}

From source file:org.opentravel.otm.forum2016.am.UploadAPIDocumentOperation.java

/**
 * @see org.opentravel.otm.forum2016.am.RESTClientOperation#execute()
 *///  ww w . j a  v  a  2 s.  co m
@Override
public APIDocument execute() throws IOException {
    HttpPost request = new HttpPost(APIPublisherConfig.getWSO2PublisherApiBaseUrl() + "/" + apiId
            + "/documents/" + documentId + "/content");

    request.setEntity(MultipartEntityBuilder.create()
            .addBinaryBody("file", contentFile, ContentType.parse(contentType), contentFile.getName()).build());
    return execute(request);
}

From source file:com.collaide.fileuploader.requests.repository.FilesRequest.java

/**
 * send a file on the server/*from ww  w . ja v  a  2s  .com*/
 *
 * @param file the file to send
 * @param id the id of the folder (on the server) to send the file. If the
 * id is equal to zero, the file is send to the root repository
 */
public void create(File file, int id) {
    HttpPost httppost = getHttpPostForCreate();
    FileBody bin = new FileBody(file);
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().addPart("repo_file[file]", bin)
            .addTextBody("authenticity_token", CurrentUser.getUser().getCsrf());
    if (id != 0) {
        reqEntity.addTextBody("repo_file[id]", String.valueOf(id));
    }
    httppost.setEntity(reqEntity.build());
    httppost.setHeader("X-CSRF-Token", CurrentUser.getUser().getCsrf());
    SendFileThread sendFile = new SendFileThread(httppost, getHttpClient());
    sendFile.start();
    getSendFileList().add(sendFile);
    if (getSendFileList().size() >= getMaxConnection()) {
        terminate();
    }
}

From source file:com.msds.km.service.Impl.YunmaiAPIDrivingLicenseRecognitionServcieiImpl.java

@Override
protected DrivingLicense recognitionInternal(File file) throws RecognitionException {
    try {/*from   ww w. j  a  v a  2s . c om*/
        HttpPost httppost = new HttpPost(POST_URL);
        FileBody fileBody = new FileBody(file);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("img", fileBody)
                .addTextBody("action", "driving").addTextBody("callbackurl", "/idcard/").build();

        httppost.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            String content = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());
            return this.parseDrivingLicense(content);
        } catch (IOException e) {
            throw new RecognitionException(
                    "can not post request to the url:" + POST_URL + ", please check the network.", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                throw new RecognitionException(
                        "can not post request to the url:" + POST_URL + ", please check the network.", e);
            }
        }
    } catch (FileNotFoundException e) {
        throw new RecognitionException(
                "the file can not founded:" + file.getAbsolutePath() + ", please check the file.", e);
    } catch (ClientProtocolException e) {
        throw new RecognitionException(
                "can not post request to the url:" + POST_URL + ", please check the network.", e);
    } catch (IOException e) {
        throw new RecognitionException(
                "can not post request to the url:" + POST_URL + ", please check the network.", e);
    }
}

From source file:ch.ralscha.extdirectspring_itest.FileUploadServiceTest.java

@Test
public void testUpload() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {//  w  w  w  .  j av a2s.c o m

        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        InputStream is = getClass().getResourceAsStream("/UploadTestFile.txt");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt");
        builder.addPart("fileUpload", cbFile);
        builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT));
        builder.addPart("extAction", new StringBody("fileUploadService", ContentType.DEFAULT_TEXT));
        builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT));
        builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT));
        builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT));

        builder.addPart("name",
                new StringBody("Jim", ContentType.create("text/plain", Charset.forName("UTF-8"))));
        builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT));
        builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT));
        builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT));

        post.setEntity(builder.build());
        response = client.execute(post);
        HttpEntity resEntity = response.getEntity();

        assertThat(resEntity).isNotNull();
        String responseString = EntityUtils.toString(resEntity);

        String prefix = "<html><body><textarea>";
        String postfix = "</textarea></body></html>";
        assertThat(responseString).startsWith(prefix);
        assertThat(responseString).endsWith(postfix);

        String json = responseString.substring(prefix.length(), responseString.length() - postfix.length());

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(json, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo("uploadTest");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("fileUploadService");
        assertThat(rootAsMap.get("tid")).isEqualTo(2);

        @SuppressWarnings("unchecked")
        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(7);
        assertThat(result.get("name")).isEqualTo("Jim");
        assertThat(result.get("firstName")).isEqualTo("Ralph");
        assertThat(result.get("age")).isEqualTo(25);
        assertThat(result.get("e-mail")).isEqualTo("test@test.ch");
        assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt");
        assertThat(result.get("fileContents")).isEqualTo("contents of upload file");
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);

        EntityUtils.consume(resEntity);

        is.close();
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:ch.ralscha.extdirectspring_itest.FileUploadControllerTest.java

@Test
public void testUpload() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    InputStream is = null;//  w  w w . j a  v a  2 s. co m
    CloseableHttpResponse response = null;

    try {
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");
        is = getClass().getResourceAsStream("/UploadTestFile.txt");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt");
        builder.addPart("fileUpload", cbFile);
        builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT));
        builder.addPart("extAction", new StringBody("fileUploadController", ContentType.DEFAULT_TEXT));
        builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT));
        builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT));
        builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT));

        builder.addPart("name",
                new StringBody("Jim", ContentType.create("text/plain", Charset.forName("UTF-8"))));
        builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT));
        builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT));
        builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT));

        post.setEntity(builder.build());
        response = client.execute(post);
        HttpEntity resEntity = response.getEntity();

        assertThat(resEntity).isNotNull();
        String responseString = EntityUtils.toString(resEntity);

        String prefix = "<html><body><textarea>";
        String postfix = "</textarea></body></html>";
        assertThat(responseString).startsWith(prefix);
        assertThat(responseString).endsWith(postfix);

        String json = responseString.substring(prefix.length(), responseString.length() - postfix.length());

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(json, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo("uploadTest");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("fileUploadController");
        assertThat(rootAsMap.get("tid")).isEqualTo(2);

        @SuppressWarnings("unchecked")
        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(7);
        assertThat(result.get("name")).isEqualTo("Jim");
        assertThat(result.get("firstName")).isEqualTo("Ralph");
        assertThat(result.get("age")).isEqualTo(25);
        assertThat(result.get("email")).isEqualTo("test@test.ch");
        assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt");
        assertThat(result.get("fileContents")).isEqualTo("contents of upload file");
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);

        EntityUtils.consume(resEntity);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(client);
    }
}

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.");
    }/*from w  ww.jav  a2  s.  co 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());
}