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.github.piotrkot.resources.CompilerResourceTest.java

/**
 * POST upload file method should be successful.
 * @throws Exception If something fails.
 *///from   w w  w . j  ava  2s  .c  o m
@Test
public void testCompileSources() throws Exception {
    final String uri = String.format("http://localhost:%d/compiler/source",
            CompilerResourceTest.APP_RULE.getLocalPort());
    Assert.assertTrue(HTTP_RESP_OK.contains(Request.Post(uri).setHeader(OK_AUTH)
            .body(MultipartEntityBuilder.create()
                    .addBinaryBody("file", new ByteArrayInputStream("hello".getBytes()),
                            ContentType.DEFAULT_BINARY, "noname")
                    .build())
            .execute().returnResponse().getStatusLine().getStatusCode()));
}

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:net.ladenthin.snowman.imager.run.uploader.Uploader.java

@Override
public void run() {
    final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager();
    final String url = cs.getSnowmanServer().getApiUrl();
    for (;;) {//from  w  ww  . j  a v  a2s. co  m
        File obtainedFile;
        for (;;) {
            if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) {
                LOGGER.trace("killFlag == true");
                return;
            }
            obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile();

            if (obtainedFile == null) {
                Imager.waitALittleBit(300);
                continue;
            } else {
                break;
            }
        }

        boolean doUpload = true;
        while (doUpload) {
            try {
                try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                    final HttpPost httppost = new HttpPost(url);
                    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM);

                    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    builder.addPart(uploadNameCameraimage, fb);
                    builder.addTextBody(uploadNameFilename, obtainedFile.getName());
                    builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername());
                    builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword());
                    builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname());

                    final HttpEntity httpEntity = builder.build();
                    httppost.setEntity(httpEntity);

                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("executing request " + httppost.getRequestLine());
                    }

                    try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("response.getStatusLine(): " + response.getStatusLine());
                        }
                        final HttpEntity resEntity = response.getEntity();
                        if (resEntity != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength());
                            }
                        }
                        final String resString = EntityUtils.toString(resEntity).trim();
                        EntityUtils.consume(resEntity);
                        if (resString.equals(responseSuccess)) {
                            doUpload = false;
                            LOGGER.trace("true: resString.equals(responseSuccess)");
                            LOGGER.trace("resString: {}", resString);
                        } else {
                            LOGGER.warn("false: resString.equals(responseSuccess)");
                            LOGGER.warn("resString: {}", resString);
                            // do not flood log files if an error occurred
                            Imager.waitALittleBit(2000);
                        }
                    }
                }
            } catch (NoHttpResponseException | SocketException e) {
                logIOExceptionAndWait(e);
            } catch (IOException e) {
                LOGGER.warn("Found unknown IOException", e);
            }
        }

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete obtainedFile {}", obtainedFile);
        }
        final boolean delete = obtainedFile.delete();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete success {}", delete);
        }
        FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile);
    }
}

From source file:com.lagrange.LabelApp.java

private static void sendPhotoToTelegramBot() {
    File file = new File(pathToImage.toUri());
    HttpEntity httpEntity = MultipartEntityBuilder.create()
            .addBinaryBody("photo", file, ContentType.create("image/jpeg"), file.getName())
            .addTextBody("chat_id", CHAT_ID).build();

    String urlSendPhoto = "https://api.telegram.org/" + BOT_ID + "/sendPhoto";

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(urlSendPhoto);
    httpPost.setEntity(httpEntity);//from  w  w w  . j av  a  2  s.  c o m
    try {
        CloseableHttpResponse response = httpclient.execute(httpPost);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Done sending photo");
}

From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java

@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain)
        throws Exception {
    boolean isText;

    HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS");

    StringBuffer proxyToURL = new StringBuffer();

    proxyToURL.append(holder.getProxyURL(uriParams));

    boolean first = true;
    for (NVP p : req.getQueryStringParams()) {
        if (first) {
            proxyToURL.append('?');
            first = false;/* w w w.j  a va2 s.  c  om*/
        } else {
            proxyToURL.append('&');
        }

        proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8"));
    }

    HttpEntity entity = null;

    if (req.isMultiPart()) {

        MultipartEntityBuilder mpeb = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String name : req.getFormParams()) {

            /*if (queryParams.contains(name)) {
               continue;
            }*/

            for (String val : req.getFormParamVals(name)) {
                //ent.addPart(name, new StringBody(val));
                mpeb.addTextBody(name, val);
            }

        }

        HashMap<String, ArrayList<FileItem>> files = req.getFiles();
        for (String name : files.keySet()) {
            for (FileItem fi : files.get(name)) {
                //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName()));

                mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName());

            }
        }

        entity = mpeb.build();

    } else if (req.isParamsInBody()) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (String paramName : req.getFormParams()) {

            for (String val : req.getFormParamVals(paramName)) {

                formparams.add(new BasicNameValuePair(paramName, val));
            }
        }

        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {

        byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY);
        ByteArrayEntity bentity = new ByteArrayEntity(msgData);
        bentity.setContentType(req.getContentType());

        entity = bentity;
    }

    MultipartRequestEntity frm;

    CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(),
            holder.getConfig());

    //HttpPost httppost = new HttpPost(proxyToURL.toString());
    HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString());

    setHeadersCookies(req, holder, httpMethod, proxyToURL.toString());

    httpMethod.setEntity(entity);

    HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX);
    HttpResponse response = httpclient.execute(httpMethod, ctx);

    postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod);

}

From source file:prodoc.StoreRem.java

/**
 * //from  w ww  .j ava  2 s .  com
 * @param Id
 * @param Ver
 * @param Bytes
 * @return
 * @throws PDException
 */
protected int Insert(String Id, String Ver, InputStream Bytes) throws PDException {
    VerifyId(Id);
    CloseableHttpResponse response2 = null;
    Node OPDObject = null;
    int Tot = 0;
    try {
        InputStreamBody bin = new InputStreamBody(Bytes, "File" + System.currentTimeMillis());
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin)
                .addTextBody(ORDER, DriverRemote.S_INSFILE).addTextBody("Id", Id).addTextBody("Ver", Ver)
                .build();
        UrlPost.setEntity(reqEntity);
        response2 = httpclient.execute(UrlPost, context);
        HttpEntity Resp = response2.getEntity();
        Bytes.close();
        Document XMLObjects = DB.parse(Resp.getContent());
        NodeList OPDObjectList = XMLObjects.getElementsByTagName("Result");
        OPDObject = OPDObjectList.item(0);
        if (OPDObject.getTextContent().equalsIgnoreCase("KO")) {
            OPDObjectList = XMLObjects.getElementsByTagName("Msg");
            if (OPDObjectList.getLength() > 0) {
                OPDObject = OPDObjectList.item(0);
                PDException.GenPDException("Server_Error", DriverGeneric.DeCodif(OPDObject.getTextContent()));
            } else
                PDException.GenPDException("Server_Error", "");
        }
    } catch (Exception ex) {
        PDException.GenPDException(ex.getLocalizedMessage(), "");
    } finally {
        DB.reset();
        if (response2 != null)
            try {
                response2.close();
            } catch (IOException ex) {
                PDException.GenPDException(ex.getLocalizedMessage(), "");
            }
    }
    return (Tot);
}

From source file:me.ixfan.wechatkit.util.HttpClientUtil.java

/**
 * POST data using the Content-Type <code>multipart/form-data</code>.
 * This enables uploading of binary files etc.
 *
 * @param url URL of request.//  www .  ja  v  a2 s .  co  m
 * @param textInputs Name-Value pairs of text inputs.
 * @param binaryInputs Name-Value pairs of binary files inputs.
 * @return JSON object of response.
 * @throws IOException If I/O error occurs.
 */
public static JsonObject sendMultipartRequestAndGetJsonResponse(String url, Map<String, String> textInputs,
        Map<String, MultipartInput> binaryInputs) throws IOException {
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    if (null != textInputs) {
        textInputs.forEach((k, v) -> multipartEntityBuilder.addTextBody(k, v));
    }
    if (null != binaryInputs) {
        binaryInputs.forEach((k, v) -> {
            if (null == v.getDataBytes()) {
                multipartEntityBuilder.addBinaryBody(k, v.getFile(), v.getContentType(), v.getFile().getName());
            } else {
                multipartEntityBuilder.addBinaryBody(k, v.getDataBytes(), v.getContentType(), v.getFilename());
            }
        });
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setEntity(multipartEntityBuilder.build());
    return httpClient.execute(post, new JsonResponseHandler());
}

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 w  w.  j  a v a2  s  .c  o  m
    }
    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: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 .  ja v  a 2 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.linkedin.pinot.common.utils.FileUploadDownloadClient.java

private static HttpUriRequest getUploadFileRequest(String method, URI uri, ContentBody contentBody,
        @Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) {
    // Build the Http entity
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addPart(contentBody.getFilename(), contentBody).build();

    // Build the request
    RequestBuilder requestBuilder = RequestBuilder.create(method).setVersion(HttpVersion.HTTP_1_1).setUri(uri)
            .setEntity(entity);/*from w  w  w. ja  v a  2  s.c  o m*/
    addHeadersAndParameters(requestBuilder, headers, parameters);
    setTimeout(requestBuilder, socketTimeoutMs);
    return requestBuilder.build();
}