Example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

Introduction

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

Prototype

HttpMultipartMode BROWSER_COMPATIBLE

To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Click Source Link

Usage

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequestWithNoMultipartConfig() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/*from   w w w. j  av a2  s.co m*/
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/0";
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.HttpHelper.java

public static void post(PlatformID platformID, String path, String paramName, InputStream data)
        throws CiliaException {

    String url = getURL(platformID, path);

    HttpPost httppost = new HttpPost(url);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    InputStreamBody bin = new InputStreamBody(data, paramName);
    reqEntity.addPart(paramName, bin);/*from   ww w .ja va2s.c o  m*/

    httppost.setEntity(reqEntity);

    // HTTP request
    HttpClient httpClient = getClient();
    try {
        httpClient.execute(httppost, new BasicResponseHandler());
        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        httpClient.getConnectionManager().shutdown();
        throw new CiliaException("can't perform HTTP PUT request", e);
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java

protected HttpPost buildCatalogRequest(String fullUri) {
    String boundary = "---------------" + UUID.randomUUID().toString();
    HttpPost post = new HttpPost(fullUri);
    post.addHeader("Accept", "application/json");
    post.addHeader("Content-Type",
            org.apache.http.entity.ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundary);
    post.addHeader("sessionId", this.catalogObjectAction.getSessionId());

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);//from www .  j a  v a  2  s .  c  om
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", new FileBody(this.catalogObjectAction.getNodeSourceJsonFile()));
    builder.addTextBody(COMMIT_MESSAGE_PARAM, this.catalogObjectAction.getCommitMessage());
    if (!this.catalogObjectAction.isRevised()) {
        builder.addTextBody(NAME_PARAM, this.catalogObjectAction.getNodeSourceName());
        builder.addTextBody(KIND_PARAM, this.catalogObjectAction.getKind());
        builder.addTextBody(OBJECT_CONTENT_TYPE_PARAM, this.catalogObjectAction.getObjectContentType());
    }
    post.setEntity(builder.build());
    return post;
}

From source file:org.retrostore.data.BlobstoreWrapperImpl.java

@Override
public void addScreenshot(String appId, byte[] data, Responder.ContentType contentType, String cookie) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(appId), "'appId' missing");
    Preconditions.checkArgument(data != null && data.length > 0, "'data' is empty");
    Preconditions.checkNotNull(contentType, "'contentType' missing");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(cookie), "'cookie' missing");

    LOG.info(String.format("About to add a screenshot blob of size %d with type %s.", data.length,
            contentType.str));//from   w  w  w . j a v a 2  s  . co m

    final String PATH_UPLOAD = "/screenshotUpload";
    String forwardTo = PATH_UPLOAD + "?appId=" + appId;

    LOG.info("Forward to: " + forwardTo);
    String uploadUrl = createUploadUrl(forwardTo);
    LOG.info("UploadUrl: " + uploadUrl);

    // It is important that we set the cookie so that we're authenticated. We do not allow
    // anonymous requests to upload screenshots.
    HttpPost post = new HttpPost(uploadUrl);
    post.setHeader("Cookie", cookie);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Note we need to use the deprecated constructor so we can use our content type.
    builder.addPart("file", new ByteArrayBody(data, contentType.str, "screenshot"));

    HttpEntity entity = builder.build();
    post.setEntity(entity);

    HttpClient client = HttpClientBuilder.create().build();
    try {
        LOG.info("POST constructed. About to make request!");
        HttpResponse response = client.execute(post);
        LOG.info("Request succeeded!");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        LOG.info(new String(out.toByteArray(), "UTF-8"));

    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Cannot make POST request.", e);
    }
}

From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java

/**
 * @param image/*from  w  ww .  ja v a2s.c  o  m*/
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws UnsupportedEncodingException
 */
private String getAsciiArt(BufferedImage image)
        throws IOException, ClientProtocolException, UnsupportedEncodingException {
    File tmpfile = File.createTempFile("bjint_", ".jpg");
    ImageIO.write(image, "jpg", tmpfile);

    // http://picascii.com/????
    // ?????
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://picascii.com/");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    entity.consumeContent();

    // ???
    HttpPost httppost = new HttpPost("http://picascii.com/upload.php");
    //HttpPost httppost = buildDefaultHttpMessage(new HttpPost("http://localhost:8080/sa-struts-tutorial/upload/"));

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    FileBody bin = new FileBody(tmpfile, "image/jpeg");
    reqEntity.addPart("imageupload", bin);
    reqEntity.addPart("MAX_FILE_SIZE", new StringBody("1000000"));
    reqEntity.addPart("url", new StringBody(""));
    reqEntity.addPart("quality", new StringBody("3"));
    reqEntity.addPart("size", new StringBody("1"));

    httppost.setEntity(reqEntity);

    response = httpclient.execute(httppost);
    String responseHtml = IOUtils.toString(response.getEntity().getContent());

    httpclient.getConnectionManager().shutdown();

    // tmpFile?
    tmpfile.delete();
    return bringOutAsciiArtString(responseHtml);
}

From source file:edu.uah.itsc.aws.RubyClient.java

public void postFile(byte[] image) throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    // HttpPost httppost = new
    // HttpPost("http://ec2-107-21-179-173.compute-1.amazonaws.com:3000/posts");
    HttpPost httppost = new HttpPost(publicURL);
    ContentBody cb = new ByteArrayBody(image, "text/plain; charset=utf8", fname);
    // ContentBody cb = new InputStreamBody(new ByteArrayInputStream(image),
    // "image/jpg", "icon.jpg");

    MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    // mpentity.addPart(cb.);
    // mpentity.addPart("utf8", new
    // StringBody((Character.toString('\u2713'))));
    mpentity.addPart("post[photo]", cb);
    mpentity.addPart("post[content]", new StringBody(desc));
    // mpentity.addPart("post[filename]", new StringBody( fname));
    mpentity.addPart("post[title]", new StringBody(title));
    mpentity.addPart("post[bucket]", new StringBody(bucket));
    mpentity.addPart("post[user]", new StringBody(User.username));
    mpentity.addPart("post[folder]", new StringBody(folder));
    mpentity.addPart("commit", new StringBody("Create Post"));
    httppost.setEntity(mpentity);/* www. java  2s.  c o m*/
    String response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8");
    System.out.println(response);
}

From source file:com.huawei.ais.demo.TokenDemo.java

/**
 * Base64???Token???/* ww  w .  j a  va  2 s  .  com*/
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrCustomsFormEnBase64(String token, String formFile) {

    // 1.?????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form";
    Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token) };
    try {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8"));
        multipartEntityBuilder.addPart("file", fileBody);

        // 2.????, POST??
        HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build());
        System.out.println(response);
        String content = IOUtils.toString(response.getEntity().getContent());
        System.out.println(content);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.apache.heron.uploader.http.HttpUploader.java

private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient)
        throws IOException, URISyntaxException {
    File file = new File(this.topologyPackageLocation);
    String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config);
    post = new HttpPost(uploaderUri);
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart(FILE, fileBody);/*from  ww w . j a  va 2  s  . c om*/
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    HttpResponse response = execute(httpclient);
    String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name());
    LOG.fine("Topology package download URI: " + responseString);

    return new URI(responseString);
}

From source file:com.phodev.http.tools.RequestEntity.java

/**
 * POST//from  ww  w  .java  2  s.c  o m
 * 
 * <pre>
 * RequestMethod{@link ConnectionHelper.RequestMethod#POST_WITH_FILE}}?
 * </pre>
 * 
 * @param postValues
 * @param files
 * @param charset
 */
public RequestEntity setPostEntitiy(List<NameValuePair> postValues, String charset, Map<String, File> files) {
    Charset c = null;
    try {
        c = Charset.forName(charset);
        Charset.defaultCharset();
    } catch (Exception e) {
        c = null;
    }
    MultipartEntity entity;
    HttpMultipartMode mode = HttpMultipartMode.BROWSER_COMPATIBLE;
    if (c == null) {
        entity = new MultipartEntity(mode);
    } else {
        entity = new MultipartEntity(mode, null, c);
    }
    postEntity = entity;
    if (postValues != null) {
        for (NameValuePair v : postValues) {
            try {
                entity.addPart(v.getName(), new StringBody(v.getValue()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    if (files != null) {
        Iterator<Entry<String, File>> iterator = files.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, File> entry = iterator.next();
            entity.addPart(entry.getKey(), new FileBody(entry.getValue()));
        }
    }
    return this;
}

From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

@Test
public void testFileUpload() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {//from   www.  j a va 2  s  . c  om

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(
                new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

    } finally {
        client.getConnectionManager().shutdown();
    }
}