Example usage for org.apache.http.entity.mime MultipartEntity addPart

List of usage examples for org.apache.http.entity.mime MultipartEntity addPart

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:com.puppetlabs.puppetdb.javaclient.impl.HttpComponentsConnector.java

@Override
public <V> V postUpload(String uri, Map<String, String> stringParts, InputStream in, String mimeType,
        String fileName, final long fileSize, Class<V> type) throws IOException {
    HttpPost request = new HttpPost(createURI(uri));
    configureRequest(request);/*from w ww  .  j a  v a  2  s.  c  o m*/

    MultipartEntity entity = new MultipartEntity();
    for (Map.Entry<String, String> entry : stringParts.entrySet())
        entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8));

    entity.addPart("file", new InputStreamBody(in, mimeType, fileName) {
        @Override
        public long getContentLength() {
            return fileSize;
        }
    });
    request.setEntity(entity);
    return executeRequest(request, type, null);
}

From source file:com.vmware.photon.controller.client.RestClient.java

public HttpResponse upload(String path, String inputFileName, Map<String, String> arguments)
        throws IOException {
    HttpClient client = getHttpClient();
    HttpPost httppost = new HttpPost(target + path);
    File file = new File(inputFileName);
    if (sharedSecret != null) {
        httppost.addHeader(AUTHORIZATION_HEADER, AUTHORIZATION_METHOD + sharedSecret);
    }/*from   w  w w.  jav a2s . c  o m*/

    MultipartEntity mpEntity = new MultipartEntity();

    FileBody cbFile = new FileBody(file, "application/octect-stream");
    for (Map.Entry<String, String> argument : arguments.entrySet()) {
        StringBody stringBody = new StringBody(argument.getValue());
        mpEntity.addPart(argument.getKey(), stringBody);
    }
    mpEntity.addPart("file", cbFile);
    httppost.setEntity(mpEntity);

    return client.execute(httppost);
}

From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java

@Override
public Promise<Void> addAttachment(final URI attachmentsUri, final InputStream inputStream,
        final String filename) {
    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.defaultCharset());
    entity.addPart(FILE_BODY_TYPE, new InputStreamBody(inputStream, filename));
    return postAttachments(attachmentsUri, entity);
}

From source file:com.dropbox.client.DropboxClient.java

/**
 * Put a file in the user's Dropbox./*from www .jav a 2  s .c  o  m*/
 */
public HttpResponse putFileStream(String root, String to_path, String name, InputStream stream, long length)
        throws DropboxException {
    String path = "/files/" + root + to_path;

    HttpClient client = getClient();

    try {
        String target = buildFullURL(secureProtocol, content_host, this.port,
                buildURL(path, API_VERSION, null));
        HttpPost req = new HttpPost(target);
        // this has to be done this way because of how oauth signs params
        // first we add a "fake" param of file=path of *uploaded* file
        // THEN we sign that.
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("file", name));
        req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        consumer.sign(req);

        // now we can add the real file multipart and we're good
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileStreamBody bin = new FileStreamBody(stream, name, length);
        entity.addPart("file", bin);
        // this resets it to the new entity with the real file
        req.setEntity(entity);

        HttpResponse resp = client.execute(req);

        resp.getEntity().consumeContent();
        return resp;
    } catch (Exception e) {
        throw new DropboxException(e);
    }
}

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");
    }//from ww w  .ja  v a2  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:com.gistlabs.mechanize.requestor.RequestBuilder.java

private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters,
        final Map<String, ContentBody> files) {
    HttpPost request = new HttpPost(uri);
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    try {/*  w  ww  . ja  v a 2  s  .c  om*/
        Charset utf8 = Charset.forName("UTF-8");
        for (Parameter param : parameters)
            if (param.isSingleValue())
                multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8));
            else
                for (String value : param.getValues())
                    multiPartEntity.addPart(param.getName(), new StringBody(value, utf8));
    } catch (UnsupportedEncodingException e) {
        throw MechanizeExceptionFactory.newException(e);
    }

    List<String> fileNames = new ArrayList<String>(files.keySet());
    Collections.sort(fileNames);
    for (String name : fileNames) {
        ContentBody contentBody = files.get(name);
        multiPartEntity.addPart(name, contentBody);
    }
    request.setEntity(multiPartEntity);
    return request;
}

From source file:org.openremote.modeler.beehive.Beehive30API.java

/**
 * Uploads resources from the given input stream to Beehive server. The Beehive REST API
 * used assumes a zip compressed stream including all relevant resources. The input stream
 * parameter must match these expectations. <p>
 *
 * The access to Beehive is authenticated using the given user's credentials.
 *
 * @param archive       zip compressed byte stream containing all the resources to upload
 *                      to Beehive//from w ww .  j a  v  a  2  s. com
 * @param currentUserAccount  The user to authenticate in Beehive, along with account information
 *
 *
 * @throws ConfigurationException
 *            If the Beehive REST URL has been incorrectly configured. Will require
 *            reconfiguration and re-deployment of the application.
 *
 * @throws NetworkException
 *            If there's an I/O error on the upload stream or the Beehive server
 *            returns an error status
 *
 */
@Override
public void uploadResources(InputStream archive, UserAccount currentUserAccount)
        throws ConfigurationException, NetworkException {
    final String ARCHIVE_NAME = "openremote.zip";

    // TODO : must be HTTPS

    Account acct = currentUserAccount.getAccount();

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost();

    addHTTPAuthenticationHeader(httpPost, currentUserAccount.getUsernamePassword().getUsername(),
            currentUserAccount.getUsernamePassword().getPassword());

    String beehiveRootRestURL = config.getBeehiveRESTRootUrl();
    String url = beehiveRootRestURL + "account/" + acct.getOid() + "/" + ARCHIVE_NAME;

    try {
        httpPost.setURI(new URI(url));
    }

    catch (URISyntaxException e) {
        throw new ConfigurationException("Incorrectly configured Beehive REST URL ''{0}'' : {1}", e,
                beehiveRootRestURL, e.getMessage());
    }

    InputStreamBody resource = new InputStreamBody(archive, ARCHIVE_NAME);

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("resource", resource);
    httpPost.setEntity(entity);

    HttpResponse response;

    try {
        response = httpClient.execute(httpPost);
    }

    catch (IOException e) {
        throw new NetworkException("Network I/O error while uploading resource artifacts to Beehive : {0}", e,
                e.getMessage());
    }

    if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
        throw new NetworkException("Failed to save resources to Beehive, status code: {0}",
                response.getStatusLine().getStatusCode());
    }

    // TODO :
    //   - should probably check other return codes explicitly here too, such as
    //     authentication errors (which is most likely not recoverable whereas
    //     a regular network connection glitch might well be)...
}

From source file:org.craftercms.social.util.UGCHttpClient.java

private HttpPost manageAttachments(String[] attachments, String ticket, String target, String textContent)
        throws UnsupportedEncodingException, URISyntaxException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpPost httppost = new HttpPost(uri);

    if (attachments.length > 0) {

        MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        File file;//ww w . j a  v a  2  s.com
        FileBody fileBody;
        for (String f : attachments) {
            file = new File(f);
            fileBody = new FileBody(file, "application/octect-stream");
            me.addPart("attachments", fileBody);
        }
        //File file = new File(attachments[0]);
        //FileBody fileBody = new FileBody(file, "application/octect-stream") ;
        //me.addPart("attachments", fileBody) ;
        me.addPart("target", new StringBody(target));
        me.addPart("textContent", new StringBody(textContent));

        httppost.setEntity(me);
    }
    return httppost;
}

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

private String createOpenGpsTrackerBundle() throws OAuthMessageSignerException, OAuthExpectationFailedException,
        OAuthCommunicationException, IOException {
    HttpPost method = new HttpPost("http://api.gobreadcrumbs.com/v1/bundles.xml");
    if (isCancelled()) {
        throw new IOException("Fail to execute request due to canceling");
    }/* ww  w  .  ja v a2 s  .c o m*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("name", new StringBody(mBundleName));
    entity.addPart("activity_id", new StringBody(mActivityId));
    entity.addPart("description", new StringBody(mBundleDescription));
    method.setEntity(entity);

    mConsumer.sign(method);
    HttpResponse response = mHttpClient.execute(method);
    HttpEntity responseEntity = response.getEntity();
    InputStream stream = responseEntity.getContent();
    String responseText = XmlCreator.convertStreamToString(stream);
    Pattern p = Pattern.compile(">([0-9]+)</id>");
    Matcher m = p.matcher(responseText);
    String bundleId = null;
    if (m.find()) {
        bundleId = m.group(1);

        ContentValues values = new ContentValues();
        values.put(MetaData.KEY, BreadcrumbsTracks.BUNDLE_ID);
        values.put(MetaData.VALUE, bundleId);
        Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata");

        mContext.getContentResolver().insert(metadataUri, values);
        mIsBundleCreated = true;
    } else {
        String text = "Unable to upload (yet) without a bunld id stored in meta-data table";
        IllegalStateException e = new IllegalStateException(text);
        handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text);
    }
    return bundleId;
}