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:com.soundcloud.playerapi.Request.java

/**
 * Builds a request with the given set of parameters and files.
 * @param method    the type of request to use
 * @param <T>       the type of request to use
 * @return HTTP request, prepared to be executed
 *//*w w  w  . j  ava  2 s .  c  om*/
public <T extends HttpRequestBase> T buildRequest(Class<T> method) {
    try {
        T request = method.newInstance();
        // POST/PUT ?
        if (request instanceof HttpEntityEnclosingRequestBase) {
            HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) request;

            final Charset charSet = java.nio.charset.Charset.forName(UTF_8);
            if (isMultipart()) {
                MultipartEntity multiPart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, // XXX change this to STRICT once rack on server is upgraded
                        null, charSet);

                if (mFiles != null) {
                    for (Map.Entry<String, Attachment> e : mFiles.entrySet()) {
                        multiPart.addPart(e.getKey(), e.getValue().toContentBody());
                    }
                }

                for (NameValuePair pair : mParams) {
                    multiPart.addPart(pair.getName(), new StringBody(pair.getValue(), "text/plain", charSet));
                }

                enclosingRequest.setEntity(
                        listener == null ? multiPart : new CountingMultipartEntity(multiPart, listener));

                request.setURI(URI.create(mResource));

                // form-urlencoded?
            } else if (mEntity != null) {
                request.setHeader(mEntity.getContentType());
                enclosingRequest.setEntity(mEntity);
                request.setURI(URI.create(toUrl())); // include the params

            } else {
                if (!mParams.isEmpty()) {
                    request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                    enclosingRequest.setEntity(new StringEntity(queryString()));
                }
                request.setURI(URI.create(mResource));
            }

        } else { // just plain GET/HEAD/DELETE/...
            if (mRange != null) {
                request.addHeader("Range", formatRange(mRange));
            }

            if (mIfNoneMatch != null) {
                request.addHeader("If-None-Match", mIfNoneMatch);
            }
            request.setURI(URI.create(toUrl()));
        }

        if (mToken != null) {
            request.addHeader(ApiWrapper.createOAuthHeader(mToken));
        }
        return request;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java

/**
 * Test HttpClient for uploading a file with non-ASCII name, if it works it means HttpClient has fixed its bug.
 *
 * Test for http://issues.apache.org/jira/browse/HTTPCLIENT-293,
 * which is related to http://sourceforge.net/p/htmlunit/bugs/535/
 *
 * @throws Exception if the test fails/*from  w  w w  .  j  a va  2  s .  c o  m*/
 */
@Test
public void uploadFileWithNonASCIIName_HttpClient() throws Exception {
    final String filename = "\u6A94\u6848\uD30C\uC77C\u30D5\u30A1\u30A4\u30EB\u0645\u0644\u0641.txt";
    final String path = getClass().getClassLoader().getResource(filename).toExternalForm();
    final File file = new File(new URI(path));
    assertTrue(file.exists());

    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/upload2", Upload2Servlet.class);

    startWebServer("./", null, servlets);
    final HttpPost filePost = new HttpPost("http://localhost:" + PORT + "/upload2");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8"));
    builder.addPart("myInput", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM));

    filePost.setEntity(builder.build());

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    final HttpResponse httpResponse = clientBuilder.build().execute(filePost);

    InputStream content = null;
    try {
        content = httpResponse.getEntity().getContent();
        final String response = new String(IOUtils.toByteArray(content));
        //this is the value with ASCII encoding
        assertFalse("3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 2E 74 78 74 <br>myInput".equals(response));
    } finally {
        IOUtils.closeQuietly(content);
    }
}

From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java

private void uploadPhoto(File photo, Integer trackId) throws IOException, OAuthMessageSignerException,
        OAuthExpectationFailedException, OAuthCommunicationException {
    HttpPost request = new HttpPost("http://api.gobreadcrumbs.com/v1/photos.xml");
    if (isCancelled()) {
        throw new IOException("Fail to execute request due to canceling");
    }//ww  w . ja v  a 2  s  .  c o m

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("name", new StringBody(photo.getName()));
    entity.addPart("track_id", new StringBody(Integer.toString(trackId)));
    //entity.addPart("description", new StringBody(""));
    entity.addPart("file", new FileBody(photo));
    request.setEntity(entity);

    mConsumer.sign(request);
    if (BreadcrumbsAdapter.DEBUG) {
        Log.d(TAG, "Execute request: " + request.getURI());
        for (Header header : request.getAllHeaders()) {
            Log.d(TAG, "   with header: " + header.toString());
        }
    }
    HttpResponse response = mHttpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    InputStream stream = responseEntity.getContent();
    String responseText = XmlCreator.convertStreamToString(stream);

    mProgressAdmin.addPhotoUploadProgress(photo.length());

    Log.i(TAG, "Uploaded photo " + responseText);
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;//from  w  w w .ja v a 2s.c  o  m
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            // CHECK RESPONSE FOR SUCCESS!!
            if (!failed && response != null
                    && response.matches(res.getString(R.string.video_bin_API_good_re))) {
                // We got back HTTP response with valid URL
                Log.d(TAG, " video bin got back URL " + response);

            } else {
                Log.d(TAG, " video bin got eror back:\n" + response);
                failed = true;
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);

                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(true);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:org.rundeck.api.ApiCall.java

private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler,
        HttpEntityEnclosingRequestBase httpPost) {
    if (null != apiPath.getAccept()) {
        httpPost.setHeader("Accept", apiPath.getAccept());
    }/*ww  w  .  j  a v  a  2 s.c o  m*/
    // POST a multi-part request, with all attachments
    if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        ArrayList<File> tempfiles = new ArrayList<>();

        //attach streams
        for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) {
            if (client.isUseIntermediateStreamFile()) {
                //transfer to file
                File f = copyToTempfile(attachment.getValue());
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), f);
                tempfiles.add(f);
            } else {
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
            }
        }
        if (tempfiles.size() > 0) {
            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        }

        //attach files
        for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) {
            multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
        }

        httpPost.setEntity(multipartEntityBuilder.build());
    } else if (apiPath.getForm().size() > 0) {
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e);
        }
    } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) {
        if (client.isUseIntermediateStreamFile()) {
            ArrayList<File> tempfiles = new ArrayList<>();
            File f = copyToTempfile(apiPath.getContentStream());
            tempfiles.add(f);
            httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType())));

            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        } else {
            InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(),
                    ContentType.create(apiPath.getContentType()));
            httpPost.setEntity(entity);
        }
    } else if (apiPath.getContents() != null && apiPath.getContentType() != null) {
        ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(),
                ContentType.create(apiPath.getContentType()));

        httpPost.setEntity(bae);
    } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) {
        httpPost.setEntity(
                new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType())));
    } else if (apiPath.getXmlDocument() != null) {
        httpPost.setHeader("Content-Type", "application/xml");
        httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument())));
    } else if (apiPath.isEmptyContent()) {
        //empty content
    } else {
        throw new IllegalArgumentException("No Form or Multipart entity for POST content-body");
    }

    return execute(httpPost, handler);
}

From source file:cl.nic.dte.net.ConexionSii.java

private RECEPCIONDTEDocument uploadEnvio(String rutEnvia, String rutCompania, File archivoEnviarSII,
        String token, String urlEnvio, String hostEnvio)
        throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(urlEnvio);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    reqEntity.addPart("rutSender", new StringBody(rutEnvia.substring(0, rutEnvia.length() - 2)));
    reqEntity.addPart("dvSender", new StringBody(rutEnvia.substring(rutEnvia.length() - 1, rutEnvia.length())));
    reqEntity.addPart("rutCompany", new StringBody(rutCompania.substring(0, (rutCompania).length() - 2)));
    reqEntity.addPart("dvCompany",
            new StringBody(rutCompania.substring(rutCompania.length() - 1, rutCompania.length())));

    FileBody bin = new FileBody(archivoEnviarSII);
    reqEntity.addPart("archivo", bin);

    httppost.setEntity(reqEntity);/*from  w ww.  j  a  v a 2  s .co m*/

    BasicClientCookie cookie = new BasicClientCookie("TOKEN", token);
    cookie.setPath("/");
    cookie.setDomain(hostEnvio);
    cookie.setSecure(true);
    cookie.setVersion(1);

    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);

    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    httppost.addHeader(new BasicHeader("User-Agent", Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE")));

    HttpResponse response = httpclient.execute(httppost, localContext);

    HttpEntity resEntity = response.getEntity();

    RECEPCIONDTEDocument resp = null;

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("", "http://www.sii.cl/SiiDte");
    XmlOptions opts = new XmlOptions();
    opts.setLoadSubstituteNamespaces(namespaces);

    resp = RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity), opts);

    return resp;
}