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:org.apache.sling.hapi.client.forms.internal.FormValues.java

public HttpEntity toMultipartEntity() {
    MultipartEntityBuilder eb = MultipartEntityBuilder.create();
    for (NameValuePair p : list.flatten()) {
        eb.addTextBody(p.getName(), p.getValue());
    }/*from w  w w.ja v  a  2s . co  m*/
    return eb.build();
}

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 w w .j av  a  2  s.  c om*/
    HttpEntity entity = entityBuilder.build();
    return Request.Post(getSuiteUrl()).body(entity).connectTimeout(timeout).socketTimeout(timeout).execute()
            .handleResponse(suiteExecutionResponseHandler);
}

From source file:org.safegees.safegees.util.HttpUrlConnection.java

public static String performPostFileCall(String requestURL, String userCredentials, File file) {

    String response = null;//from w  ww  . j a  va  2 s. co  m
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
    reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    //reqEntity.addPart("avatar", new FileBody(file, ContentType.MULTIPART_FORM_DATA));
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(requestURL);
    httppost.addHeader(KEY_HEADER_AUTHORIZED, userCredentials);
    httppost.addHeader("ContentType", "image/png");
    httppost.addHeader("Referer", "https://safegees.appspot.com/v1/user/image/upload/");
    httppost.addHeader("Origin", "https://safegees.appspot.com");
    httppost.addHeader("Upgrade-Insecure-Requests", "1");
    httppost.addHeader("User-Agent",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
    reqEntity.addBinaryBody("avatar", file, ContentType.create("image/png"), file.getName());
    httppost.setEntity(reqEntity.build());
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpclient.execute(httppost);
        Log.e("IMAGE", httpResponse.getStatusLine().getStatusCode() + ":"
                + httpResponse.getStatusLine().getReasonPhrase());
        //response = EntityUtils.toString(httpResponse.getEntity());
        response = httpResponse.getStatusLine().getReasonPhrase();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (httpResponse.getStatusLine().getStatusCode() == 200)
        return response;
    return null;
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * post/*from  w w  w  .j  av a  2  s.c o m*/
 *
 * @param uri
 * @param map
 * @return
 */
public static String post(String uri, Map<String, Object> map) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    HttpEntity httpEntity = null;
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value != null && value instanceof String) {
            String param = (String) value;
            multipartEntityBuilder.addTextBody(key, param, ContentType.create("text/plain", CHARSET));
        }
        if (value != null && value instanceof File) {
            multipartEntityBuilder.addBinaryBody(key, (File) value);
        }
    }
    try {
        httpPost.setEntity(multipartEntityBuilder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            httpEntity = httpResponse.getEntity();
        }
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    try {
        return EntityUtils.toString(httpEntity, CHARSET);
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:it.polimi.diceH2020.plugin.net.NetworkManager.java

/**
 * Sends to the backend the models to be simulated
 * /*from  w  w w .  j a v  a 2 s .  c om*/
 * @param files
 *            The model files
 * @param scenario
 *            The scenario parameter
 * @throws UnsupportedEncodingException
 */
public void sendModel(List<File> files, String scenario) throws UnsupportedEncodingException {
    HttpClient httpclient = HttpClients.createDefault();
    HttpResponse response;
    HttpPost post = new HttpPost(uploadRest);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("scenario", new StringBody(scenario, ContentType.DEFAULT_TEXT));

    for (File file : files) {
        builder.addPart("file[]", new FileBody(file));
    }

    post.setEntity(builder.build());
    try {
        response = httpclient.execute(post);
        String json = EntityUtils.toString(response.getEntity());
        HttpPost repost = new HttpPost(this.getLink(json));
        response = httpclient.execute(repost);
        String js = EntityUtils.toString(response.getEntity());
        parseJson(js);
        System.out.println("Code : " + response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            System.err.println("Error: POST not succesfull");
        } else {
        }
        System.out.println(Configuration.getCurrent().getID());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadAlbumRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//from   w w  w  . ja  v a2  s .  c  om
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(File imageFile, String uploadId)
        throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static int upload(File file, String url, String schema, StringBuilder response) throws IOException {
    HttpPost post = new HttpPost(url);
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        MultipartEntityBuilder b = MultipartEntityBuilder.create();
        if (schema != null) {
            b.addPart("schema", new StringBody(schema, ContentType.TEXT_PLAIN));
        }/*from  w w w.j  a  v  a2s. c  o m*/
        b.addPart("data", new FileBody(file));
        post.setEntity(b.build());
        HttpResponse r = client.execute(post);
        if (response != null) {
            InputStream is = r.getEntity().getContent();
            int n;
            while ((n = is.read()) > 0) {
                response.append((char) n);
            }
            is.close();
        }
        return r.getStatusLine().getStatusCode();
    }
}

From source file:apiserver.core.connectors.coldfusion.ColdFusionHttpBridge.java

public ResponseEntity invokeFilePost(String cfcPath_, String method_, Map<String, Object> methodArgs_)
        throws ColdFusionException {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        HttpHost host = new HttpHost(cfHost, cfPort, cfProtocol);
        HttpPost method = new HttpPost(validatePath(cfPath) + cfcPath_);

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

        if (methodArgs_ != null) {
            for (String s : methodArgs_.keySet()) {
                Object obj = methodArgs_.get(s);

                if (obj != null) {
                    if (obj instanceof String) {
                        me.addTextBody(s, (String) obj);
                    } else if (obj instanceof Integer) {
                        me.addTextBody(s, ((Integer) obj).toString());
                    } else if (obj instanceof File) {
                        me.addBinaryBody(s, (File) obj);
                    } else if (obj instanceof IDocument) {
                        me.addBinaryBody(s, ((IDocument) obj).getFile());
                        //me.addTextBody( "name", ((IDocument)obj).getFileName() );
                        //me.addTextBody("contentType", ((IDocument) obj).getContentType().contentType );
                    } else if (obj instanceof IDocument[]) {
                        for (int i = 0; i < ((IDocument[]) obj).length; i++) {
                            IDocument iDocument = ((IDocument[]) obj)[i];
                            me.addBinaryBody(s, iDocument.getFile());
                            //me.addTextBody("name", iDocument.getFileName() );
                            //me.addTextBody("contentType", iDocument.getContentType().contentType );
                        }/*from w  w  w . j a v a  2  s. com*/

                    } else if (obj instanceof BufferedImage) {

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        ImageIO.write((BufferedImage) obj, "jpg", baos);

                        String _fileName = (String) methodArgs_.get(ApiServerConstants.FILE_NAME);
                        String _mimeType = ((MimeType) methodArgs_.get(ApiServerConstants.CONTENT_TYPE))
                                .getExtension();
                        ContentType _contentType = ContentType.create(_mimeType);
                        me.addBinaryBody(s, baos.toByteArray(), _contentType, _fileName);
                    } else if (obj instanceof byte[]) {
                        me.addBinaryBody(s, (byte[]) obj);
                    } else if (obj instanceof Map) {
                        ObjectMapper mapper = new ObjectMapper();
                        String _json = mapper.writeValueAsString(obj);

                        me.addTextBody(s, _json);
                    }
                }
            }
        }

        HttpEntity httpEntity = me.build();
        method.setEntity(httpEntity);

        HttpResponse response = httpClient.execute(host, method);//, responseHandler);

        // Examine the response status
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputStream = entity.getContent();
                //return inputStream;

                byte[] _body = IOUtils.toByteArray(inputStream);

                MultiValueMap _headers = new LinkedMultiValueMap();
                for (Header header : response.getAllHeaders()) {
                    if (header.getName().equalsIgnoreCase("content-length")) {
                        _headers.add(header.getName(), header.getValue());
                    } else if (header.getName().equalsIgnoreCase("content-type")) {
                        _headers.add(header.getName(), header.getValue());

                        // special condition to add zip to the file name.
                        if (header.getValue().indexOf("text/") > -1) {
                            //add nothing extra
                        } else if (header.getValue().indexOf("zip") > -1) {
                            if (methodArgs_.get("file") != null) {
                                String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                                _headers.add("Content-Disposition",
                                        "attachment; filename=\"" + _fileName + ".zip\"");
                            }
                        } else if (methodArgs_.get("file") != null) {
                            String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                            _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + "\"");
                        }

                    }
                }

                return new ResponseEntity(_body, _headers, org.springframework.http.HttpStatus.OK);
                //Map json = (Map)deSerializeJson(inputStream);
                //return json;
            }
        }

        MultiValueMap _headers = new LinkedMultiValueMap();
        _headers.add("Content-Type", "text/plain");
        return new ResponseEntity(response.getStatusLine().toString(), _headers,
                org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

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

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //from   ww  w .jav a2 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();
}