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:fm.smart.r1.CreateSoundActivity.java

public CreateSoundResult createSound(File file, String media_entity, String author, String author_url,
        String attribution_license_id, String item_id, String id, String to_record) {
    String http_response = "";
    int status_code = 0;
    HttpClient client = null;/*  www . j  a  va 2  s.c  o  m*/
    String type = "sentence";
    String location = "";
    try {
        client = new DefaultHttpClient();
        if (sound_type.equals(Integer.toString(R.id.cue_sound))) {
            type = "item";
        }
        HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds.json");

        String auth = LoginActivity.username(this) + ":" + LoginActivity.password(this);
        byte[] bytes = auth.getBytes();
        post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes)));

        post.setHeader("Host", "api.smart.fm");

        FileBody bin = new FileBody(file, "audio/amr");
        StringBody media_entity_part = new StringBody(media_entity);
        StringBody author_part = new StringBody(author);
        StringBody author_url_part = new StringBody(author_url);
        StringBody attribution_license_id_part = new StringBody(attribution_license_id);
        StringBody id_part = new StringBody(id);
        StringBody api_key_part = new StringBody(Main.API_KEY);
        StringBody version_part = new StringBody("2");
        StringBody text_part = new StringBody(to_record);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("sound[file]", bin);
        reqEntity.addPart("media_entity", media_entity_part);
        reqEntity.addPart("author", author_part);
        reqEntity.addPart("author_url", author_url_part);
        reqEntity.addPart("attribution_license_id", attribution_license_id_part);
        reqEntity.addPart(type + "_id", id_part);
        reqEntity.addPart("api_key", api_key_part);
        reqEntity.addPart("text", text_part);
        reqEntity.addPart("v", version_part);

        post.setEntity(reqEntity);

        Header[] array = post.getAllHeaders();
        for (int i = 0; i < array.length; i++) {
            Log.d("DEBUG", array[i].toString());
        }

        Log.d("CreateSoundActivity", "executing request " + post.getRequestLine());
        HttpResponse response = client.execute(post);
        status_code = response.getStatusLine().getStatusCode();
        HttpEntity resEntity = response.getEntity();

        Log.d("CreateSoundActivity", "----------------------------------------");
        Log.d("CreateSoundActivity", response.getStatusLine().toString());
        array = response.getAllHeaders();
        String header;
        for (int i = 0; i < array.length; i++) {
            header = array[i].toString();
            if (header.equals("Location")) {
                location = header;
            }
            Log.d("CreateSoundActivity", header);
        }
        if (resEntity != null) {
            Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength());
            Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked());
        }
        long length = response.getEntity().getContentLength();
        byte[] response_bytes = new byte[(int) length];
        response.getEntity().getContent().read(response_bytes);
        Log.d("CreateSoundActivity", new String(response_bytes));
        http_response = new String(response_bytes);
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        // HttpEntity entity = response1.getEntity();
    } catch (IOException e) {
        /* Reset to Default image on any error. */
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return new CreateSoundResult(status_code, http_response, location);
}

From source file:org.opencastproject.loadtest.impl.IngestJob.java

/**
 * Use the TrustedHttpClient from matterhorn to ingest the mediapackage.
 * /*from www.  j  av  a2 s . co m*/
 * @param workingDirectory
 *          The path to the working directory for the LoadTesting.
 * @param mediaPackageLocation
 *          The location of the mediapackage we want to ingest.
 */
private void ingestMediaPackageWithJava(String workingDirectory, String mediaPackageLocation,
        String workflowID) {
    logger.info("Ingesting recording with HttpTrustedClient: {}", id);
    try {
        URL url = new URL(loadTest.getCoreAddress() + "/ingest/addZippedMediaPackage");
        File fileDesc = new File(mediaPackageLocation);
        // Set the file as the body of the request
        MultipartEntity entities = new MultipartEntity();
        // Check to see if the properties have an alternate workflow definition attached
        String workflowInstance = id;

        try {
            entities.addPart("workflowDefinitionId", new StringBody(workflowID, Charset.forName("UTF-8")));
            entities.addPart("workflowInstanceId", new StringBody(workflowInstance, Charset.forName("UTF-8")));
            entities.addPart(fileDesc.getName(),
                    new InputStreamBody(new FileInputStream(fileDesc), fileDesc.getName()));
        } catch (FileNotFoundException ex) {
            logger.error("Could not find zipped mediapackage " + fileDesc.getAbsolutePath());
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("This system does not support UTF-8", e);
        }

        logger.debug("Ingest URL is " + url.toString());
        HttpPost postMethod = new HttpPost(url.toString());
        postMethod.setEntity(entities);

        // Send the file
        HttpResponse response = null;
        int retValue = -1;
        try {
            logger.debug(
                    "Sending the file " + fileDesc.getAbsolutePath() + " with a size of " + fileDesc.length());
            response = client.execute(postMethod);
        } catch (TrustedHttpClientException e) {
            logger.error("Unable to ingest recording {}, message reads: {}.", id, e.getMessage());
        } catch (NullPointerException e) {
            logger.error("Unable to ingest recording {}, null pointer exception!", id);
        } finally {
            if (response != null) {
                retValue = response.getStatusLine().getStatusCode();
                client.close(response);
            } else {
                retValue = -1;
            }
        }

        if (retValue == HttpURLConnection.HTTP_OK) {
            logger.info(id + " successfully ingested.");
        }

        else {
            logger.info(id + " ingest failed with return code " + retValue + " and status line "
                    + response.getStatusLine().toString());
        }

    } catch (MalformedURLException e) {
        logger.error("Malformed URL for ingest target \"" + loadTest.getCoreAddress()
                + "/ingest/addZippedMediaPackage\"");
    }
}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

public void executeMultipartPost() throws Exception {

    try {//  w w  w  .  j av a2  s. c  om

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost("http://192.168.14.102/index.php/photos/upload");

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

        Session.image.compress(Bitmap.CompressFormat.PNG, 100, byteStream);

        byte[] buffer = byteStream.toByteArray();

        ByteArrayBody body = new ByteArrayBody(buffer, "profile_image");

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("gambar", body);
        entity.addPart("nama", new StringBody(Session.name)); //POST nama
        entity.addPart("keterangan", new StringBody(Session.caption)); //POST keterangan
        entity.addPart("lat", new StringBody(lat)); //POST keterangan
        entity.addPart("lon", new StringBody(longt)); //POST keterangan
        post.setEntity(entity);

        System.out.println("post entity length " + entity.getContentLength());
        ResponseHandler handler = new BasicResponseHandler();

        String response = client.execute(post, handler);

    } catch (Exception e) {

        Log.e(e.getClass().getName(), e.getMessage());

    }

}

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

@Override
public Promise<Void> addAttachments(final URI attachmentsUri, final AttachmentInput... attachments) {
    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.defaultCharset());
    for (final AttachmentInput attachmentInput : attachments) {
        entity.addPart(FILE_BODY_TYPE,
                new InputStreamBody(attachmentInput.getInputStream(), attachmentInput.getFilename()));
    }//from  www.j  a v a 2  s . co  m
    return postAttachments(attachmentsUri, entity);
}

From source file:org.s1.testing.httpclient.TestHttpClient.java

/**
 *
 * @param u/*from   w w w.j a  v a2s . co  m*/
 * @param data
 * @param name
 * @param contentType
 * @return
 */
public HttpResponseBean uploadFile(String u, InputStream data, String name, String contentType) {
    Map<String, Object> headers = new HashMap<String, Object>();

    u = getURL(u, null);
    HttpPost post = new HttpPost(u);
    try {
        MultipartEntity request = new MultipartEntity();
        ContentBody body = new InputStreamBody(data, contentType, name);
        request.addPart("file", body);
        post.setEntity(request);
        for (String h : headers.keySet()) {
            post.setHeader(h, "" + headers.get(h));
        }

        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);

        HttpResponse resp = null;
        try {
            resp = client.execute(host, post, context);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        Map<String, String> rh = new HashMap<String, String>();
        for (Header h : resp.getAllHeaders()) {
            rh.put(h.getName(), h.getValue());
        }
        try {
            HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh,
                    EntityUtils.toByteArray(resp.getEntity()));
            printIfError(u, r);
            return r;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java

public static MultipartEntity buildPictureData(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (bitmap.getWidth() > 512 || bitmap.getHeight() > 512) {
        float scale = Math.min(512f / bitmap.getWidth(), 512f / bitmap.getHeight());
        bitmap = Bitmap.createScaledBitmap(bitmap, (int) (scale * bitmap.getWidth()),
                (int) (scale * bitmap.getHeight()), false);
    }/*from ww  w . jav  a2 s. c o  m*/
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
    byte[] bytes = baos.toByteArray();
    MultipartEntity data = new MultipartEntity();
    data.addPart("picture", new ByteArrayBody(bytes, "image/jpg", "image.jpg"));
    return data;
}

From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java

/**
 * Check if upload file has already been uploaded. Do nothing, if file is
 * missing.//from   w  w w  .j  a va  2 s.  c  o  m
 * 
 * @throws UploadFailedException
 *             If something went wrong sending/receiving the request to/from
 *             the lookaside cache.
 * @throws FileAvailableInLookasideCacheException
 *             If the upload candidate file is already present in the
 *             lookaside cache.
 */
private void checkSourceAvailable() throws FileAvailableInLookasideCacheException, UploadFailedException {
    HttpClient client = getClient();
    try {
        String uploadURI = null;
        uploadURI = this.projectRoot.getLookAsideCache().getUploadUrl().toString();
        assert uploadURI != null;

        if (fedoraSslEnabled) {
            // user requested Fedora SSL enabled client
            try {
                client = fedoraSslEnable(client);
            } catch (GeneralSecurityException e) {
                throw new UploadFailedException(e.getMessage(), e);
            }
        } else if (trustAllSSLEnabled) {
            // use accept all SSL enabled client
            try {
                client = trustAllSslEnable(client);
            } catch (GeneralSecurityException e) {
                throw new UploadFailedException(e.getMessage(), e);
            }
        }

        HttpPost post = new HttpPost(uploadURI);

        // provide hint which URL is going to be used
        FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance();
        logger.logDebug(NLS.bind(FedoraPackagerText.UploadSourceCommand_usingUploadURLMsg, uploadURI));

        // Construct the multipart POST request body.
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart(FILENAME_PARAM_NAME, new StringBody(fileToUpload.getName()));
        reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName()));
        reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload)));

        post.setEntity(reqEntity);

        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new UploadFailedException(response.getStatusLine().getReasonPhrase(), response);
        } else {
            String resString = ""; //$NON-NLS-1$
            if (resEntity != null) {
                try {
                    resString = parseResponse(resEntity);
                } catch (IOException e) {
                    // ignore
                }
                EntityUtils.consume(resEntity); // clean up resources
            }
            // If this file has already been uploaded bail out
            if (resString.toLowerCase().equals(RESOURCE_AVAILABLE)) {
                throw new FileAvailableInLookasideCacheException(fileToUpload.getName());
            } else if (resString.toLowerCase().equals(RESOURCE_MISSING)) {
                // check passed
                return;
            } else {
                // something is fishy
                throw new UploadFailedException(FedoraPackagerText.somethingUnexpectedHappenedError);
            }
        }
    } catch (IOException e) {
        throw new UploadFailedException(e.getMessage(), e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java

/**
 * Upload a missing file to the lookaside cache.
 * //from  w ww .  j a v a  2s .  co m
 * Pre: upload file is missing as determined by
 * {@link UploadSourceCommand#checkSourceAvailable()}.
 * 
 * @param subMonitor
 * @return The result of the upload.
 */
private UploadSourceResult upload(final IProgressMonitor subMonitor) throws UploadFailedException {
    HttpClient client = getClient();
    try {
        String uploadUrl = projectRoot.getLookAsideCache().getUploadUrl().toString();

        if (fedoraSslEnabled) {
            // user requested a Fedora SSL enabled client
            client = fedoraSslEnable(client);
        } else if (trustAllSSLEnabled) {
            // use an trust-all SSL enabled client
            client = trustAllSslEnable(client);
        }

        HttpPost post = new HttpPost(uploadUrl);
        FileBody uploadFileBody = new FileBody(fileToUpload);
        // For the actual upload we must not provide the
        // "filename" parameter (FILENAME_PARAM_NAME). Otherwise,
        // the file won't be stored in the lookaside cache.
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart(FILE_PARAM_NAME, uploadFileBody);
        reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName()));
        reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload)));

        // Not sure why it's ~ content-length * 2, but that's what it is...
        final long totalsize = reqEntity.getContentLength() * 2;
        subMonitor.beginTask(NLS.bind(FedoraPackagerText.UploadSourceCommand_uploadingFileSubTaskName,
                fileToUpload.getName()), 100 /* use percentage */);
        subMonitor.worked(0);

        // Custom listener for progress reporting of the file upload
        IRequestProgressListener progL = new IRequestProgressListener() {

            private int count = 0;
            private int worked = 0;
            private int updatedWorked = 0;

            @Override
            public void transferred(final long bytesWritten) {
                count++;
                worked = updatedWorked;
                if (subMonitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
                // Since this listener may be called *a lot*, don't
                // do the calculation to often.
                if ((count % 1024) == 0) {
                    updatedWorked =
                            // multiply by 85 (instead of 100) since upload
                            // progress cannot be 100% accurate.
                            (int) ((double) bytesWritten / totalsize * 85);
                    if (updatedWorked > worked) {
                        worked = updatedWorked;
                        subMonitor.worked(updatedWorked);
                    }
                }
            }
        };
        // We need to wrap the entity which we want to upload in our
        // custom entity, which allows for progress listening.
        CoutingRequestEntity countingEntity = new CoutingRequestEntity(reqEntity, progL);
        post.setEntity(countingEntity);

        // TODO: This may throw some certificate exception. We should
        // handle this case and throw a specific exception in order to
        // report this to the user. I.e. advise to use use $ fedora-cert -n
        HttpResponse response = client.execute(post);

        subMonitor.done();
        return new UploadSourceResult(response);
    } catch (IOException e) {
        throw new UploadFailedException(e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new UploadFailedException(e.getMessage(), e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:org.hk.jt.client.core.Request.java

private HttpResponse execPost() throws URISyntaxException, InvalidKeyException, UnsupportedEncodingException,
        NoSuchAlgorithmException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpPost httpPost = new HttpPost();
    httpPost.setURI(new URI(requestIf.getUrl()));
    httpPost.setHeader("Authorization", createAuthorizationValue());

    if (postParameter != null && !postParameter.isEmpty()) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : postParameter.keySet()) {
            params.add(new BasicNameValuePair(key, postParameter.get(key)));
        }/*  w w w.  j  a v a 2s . c  o m*/
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    }

    if (requestIf.getFiles() != null) {
        final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        List<NameValuePair> fileList = requestIf.getFiles();
        if (fileList != null && !fileList.isEmpty()) {
            for (NameValuePair val : fileList) {
                File file = new File(val.getValue());
                entity.addPart(val.getName(), new FileBody(file, CONTENTTYPE_BINARY));
            }
        }
        httpPost.setEntity(entity);
    }
    httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    return client.execute(httpPost);
}

From source file:com.frentix.restapi.RestConnection.java

/**
 * Attach file to POST request./* ww  w.j  a v  a 2  s  . c  o  m*/
 * 
 * @param post the request
 * @param filename the filename field
 * @param file the file
 * @throws UnsupportedEncodingException
 */
public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file)
        throws UnsupportedEncodingException {

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("filename", new StringBody(filename));
    FileBody fileBody = new FileBody(file, "application/octet-stream");
    entity.addPart("file", fileBody);
    post.setEntity(entity);
}